298
votes

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

6

6 Answers

553
votes
 NSLog(@"%@",[NSThread callStackSymbols]);

This code works on any thread.

35
votes

n13's answer didn't quite work - I modified it slightly to come up with this

#import <UIKit/UIKit.h>

#import "AppDelegate.h"

int main(int argc, char *argv[])
{
    @autoreleasepool {
        int retval;
        @try{
            retval = UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
        }
        @catch (NSException *exception)
        {
            NSLog(@"Gosh!!! %@", [exception callStackSymbols]);
            @throw;
        }
        return retval;
    }
}
9
votes

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.

6
votes

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]
2
votes

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.

1
votes

In swift print this way:

print("stack trace:\(Thread.callStackSymbols)")