views:

1686

answers:

4

I'd like to log the call trace during certain points, like failed assertions, or uncaught exceptions.

UPDATE: Thanks for the answers.. followup question... how do you do the same in a thread other than the main thread?

Neither method properly displayed the stack in such a case. The output is nonsensical wrt to the current context. However if I break in the debugger on the same point, I see the correct trace for that thread. Unfortunately I cannot reproduce the problem in the debugger that I need a stack trace for.

+2  A: 

This pretty much tells you what to do.

Essentially you need to set up the applications exception handling to log, something like

#import <ExceptionHandling/NSExceptionHandler.h>

[[NSExceptionHandler defaultExceptionHandler] setExceptionHandlingMask: NSLogUncaughtExceptionMask | NSLogUncaughtSystemExceptionMask | NSLogUncaughtRuntimeErrorMask]
Max Stewart
Note, though that this will only work within a registered exception handler (not, e.g., in a @catch block)
Barry Wark
+1  A: 

For exceptions, you can use the NSStackTraceKey member of the exception's userInfo dictionary to do this. See Controlling a Program's Response to Exceptions on Apple's website.

Ben Gottlieb
+7  A: 

Cocoa already logs the stack trace on uncaught exceptions to the console although they're just raw memory addresses. If you want symbolic information in the console there's some sample code from Apple.

If you want to generate a stack trace at an arbitrary point in your code (and you're on Leopard), see the backtrace man page. Before Leopard, you actually had to dig through the call stack itself.

vt
Apparently available in iOS 4 but not 3.2. Here's what I used, shamelessly copied from the backtrace man page:#include <execinfo.h>... void* callstack[128]; int i, frames = backtrace(callstack, 128); char** strs = backtrace_symbols(callstack, frames); for (i = 0; i < frames; ++i) { printf("%s\n", strs[i]); } free(strs);
mharper
+10  A: 
 NSLog(@"%@",[NSThread callStackSymbols]);

works on any thread.

smokris
New in Mac OS X 10.6, which didn't exist when this question was originally asked. For pre-Snow-Leopard, use the `backtrace` and `backtrace_symbols` functions; see the backtrace(3) manpage.
Peter Hosey