从异常中获取回溯而不重新引发异常
我正在使用 Twister 构建服务器。我还维护服务器错误日志。问题是,如果我让异常在堆栈中一直运行,它会崩溃当前连接并断开用户连接,所以显然我附加了一个裸露的除了以获取其他所有内容。
一旦我捕获到某些内容,有没有办法将回溯作为字符串获取,以便我可以将其存储在某处/自己打印它,而无需引发它并让Python在程序崩溃时为我打印它?
I'm using Twister to build a server. I am also maintaining a server error log. The issue is that if I let an exception run all the way up the stack, it'll crash the current connection and disconnect the user, so obviously I attach a bare except to grab everything else.
Once I've caught something, is there a way to get the traceback as a string so that I can store it somewhere/print it myself without raising it and letting Python print it for me once the program crashes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
回溯模块包含一些用于打印和检查回溯的辅助函数(例如,traceback.print_tb) - 但重要的是回溯信息本身存储在模块 sys 上的“解释器全局”变量中 - sys.exc_traceback 。
引用自:
http://docs.python.org/reference/compound_stmts.html#try< /a>
您可以将 sys.exc_traceback 对象作为参数传递给traceback.print_tb,以将回溯打印到 except 子句中的标准输出。
The traceback module contains some helper functions for printing and inspecting the traceback (for exameble, traceback.print_tb ) - but the important thing is that the traceback information itself is stored in a "interpreter global" variable - sys.exc_traceback, on the module sys.
Quoting from:
http://docs.python.org/reference/compound_stmts.html#try
You can pass the sys.exc_traceback object as a parameter to traceback.print_tb to have the traceback printed to stdout within the except clause.
使用日志记录模块,您可以将回溯记录到文件中:
Using the logging module, you could log the traceback to a file:
试试这个:
这应该可以解决问题并打印完整的堆栈跟踪。
Try this:
That should do the trick and print full stack traces too.
是的,有一个模块。
traceback
模块包含打印或格式化异常信息的函数,或者返回原始堆栈帧的函数,以便您可以对它们执行任何您想要的操作。不过,对于相当复杂的应用程序,我实际上建议使用日志系统而不是普通的旧
traceback
函数。特别是方法logging.Logger.exception
< /a> 会将有关异常的信息写入您(或软件的用户)配置的任何日志记录目标。默认格式化程序只会打印出回溯,就像 Python 在控制台上一样,但是您可以通过创建Formatter
并覆盖format_exception
方法。如果您需要回溯函数来格式化异常输出,则您的重写方法是调用它们的地方。Yep, there's a module for that. The
traceback
module contains functions to print or format exception information, or to return the raw stack frames so you can do whatever you want with them.For a reasonably sophisticated application, though, I would actually recommend using the logging system instead of plain old
traceback
functions. In particular the methodlogging.Logger.exception
will write information about the exception to whatever logging destination you (or your software's user) has configured. The default formatter will just print out a traceback, as Python would on the console, but you can customize the display of exceptions in your log by creating aFormatter
and overriding theformat_exception
method. Your overridden method is the place to calltraceback
functions if you need them to format the exception output.