I'd like to log the call trace during certain points, like failed assertions, or uncaught exceptions.
I'd like to log the call trace during certain points, like failed assertions, or uncaught exceptions.
This code works on any thread:
NSLog(@"%@", NSThread.callStackSymbols);
Returns an array containing the call stack symbols. Each element is an
NSStringobject with a value in a format determined by thebacktrace_symbols()function.
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.
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]
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.