如何在 Cocoa 中将堆栈跟踪打印到控制台/日志?
我想在某些点记录调用跟踪,例如失败的断言或未捕获的异常。
I'd like to log the call trace during certain points, like failed assertions, or uncaught exceptions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
此代码适用于任何线程:
This code works on any thread:
n13 的答案不太有效 - 我稍微修改了一下就得到了这个
n13's answer didn't quite work - I modified it slightly to come up with this
Cocoa 已经将未捕获异常的堆栈跟踪记录到控制台,尽管它们只是原始内存地址。 如果您想在控制台中获得符号信息,可以使用一些 来自 Apple 的示例代码。
如果您想在代码中的任意点生成堆栈跟踪(并且您使用的是 Leopard),请参阅 backtrace 手册页。 在 Leopard 之前,您实际上必须深入挖掘调用堆栈本身。
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:
对于异常,您可以使用异常的 userInfo 字典的 NSStackTraceKey 成员来执行此操作。 请参阅控制Apple 网站上的程序对异常的响应。
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.
以这种方式快速打印:
In swift print this way:
如果你想将它作为 NSString 获取。
If you want to get it as NSString.