objective-c 您如何将堆栈跟踪打印到 Cocoa 中的控制台/日志?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/220159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you print out a stack trace to the console/log in Cocoa?
提问by robottobor
I'd like to log the call trace during certain points, like failed assertions, or uncaught exceptions.
我想在某些点记录调用跟踪,例如失败的断言或未捕获的异常。
回答by smokris
NSLog(@"%@",[NSThread callStackSymbols]);
This code works on any thread.
此代码适用于任何线程。
回答by Zayin Krige
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;
}
}
回答by vt.
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 codefrom Apple.
Cocoa 已经将未捕获异常的堆栈跟踪记录到控制台,尽管它们只是原始内存地址。如果您想要控制台中的符号信息,则有一些来自 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.
如果您想在代码中的任意点生成堆栈跟踪(并且您在 Leopard 上),请参阅回溯手册页。在 Leopard 之前,您实际上必须深入研究调用堆栈本身。
回答by Max Stewart
Thispretty 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]
回答by Ben Gottlieb
For exceptions, you can use the NSStackTraceKey member of the exception's userInfo dictionary to do this. See Controlling a Program's Response to Exceptionson Apple's website.
对于异常,您可以使用异常的 userInfo 字典的 NSStackTraceKey 成员来执行此操作。请参阅Apple 网站上的控制程序对异常的响应。
回答by Deepak
In swift print this way:
以这种方式快速打印:
print("stack trace:\(Thread.callStackSymbols)")

