如何將堆疊跟蹤列印到Cocoa中的控制檯/日誌?

2020-08-10 12:39:01

本文翻譯自:How do you print out a stack trace to the console/log in Cocoa?

我想在某些點記錄呼叫跟蹤,例如失敗的斷言或未捕獲的異常。


#1樓

參考:https://stackoom.com/question/VgX/如何將堆疊跟蹤列印到Cocoa中的控制檯-日誌


#2樓

n13's answer didn't quite work - I modified it slightly to come up with this n13的答案並不是很有效 - 我稍微修改了它以得出這個

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

#3樓

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]

#4樓

For exceptions, you can use the NSStackTraceKey member of the exception's userInfo dictionary to do this. 對於異常,您可以使用異常的userInfo字典的NSStackTraceKey成員來執行此操作。 See Controlling a Program's Response to Exceptions on Apple's website. 請參閱Apple網站上的控製程式對例外的響應


#5樓

Cocoa already logs the stack trace on uncaught exceptions to the console although they're just raw memory addresses. Cocoa已經將未捕獲的異常的堆疊跟蹤記錄到控制檯,儘管它們只是原始記憶體地址。 If you want symbolic information in the console there's some sample code from Apple. 如果您想在控制檯中獲得符號資訊,那麼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. 如果要在程式碼中的任意點生成堆疊跟蹤(並且您在Leopard上),請參閱backtrace手冊頁。 Before Leopard, you actually had to dig through the call stack itself. 在Leopard之前,你實際上不得不深入挖掘呼叫堆疊本身。


#6樓

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

此程式碼適用於任何執行緒。