Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you print out a stack trace to the console/log in Cocoa?

People also ask

Which console method can be used to print the stack trace?

trace() The console. trace() method outputs a stack trace to the Web console.

How do I print exception stack trace in log file?

To print a stack trace to log you Should declare logger and method info(e. toString()) or log(Level.INFO, e. toString()). Logging is the process of writing log messages during the execution of a program to get error and warning messages as well as info messages.

Where is stack trace in developer console?

Show activity on this post. If you go to set log panels and select "Execution Stack" and "Execution Log", it should bring up a stack trace panel next to the standard log panel. Clicking any line in the Log Panel will load up the stack for that line.

How do I print a stack trace in Swift?

In Objective-C, you can print the call stack by doing the following: NSLog(@"%@", [NSThread callStackSymbols]);


This code works on any thread:

NSLog(@"%@", NSThread.callStackSymbols);

Returns an array containing the call stack symbols. Each element is an NSString object with a value in a format determined by the backtrace_symbols() function.


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;
    }
}

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]