如何记录python异常? [英] How to log python exception?
问题描述
我已经看过一些选项,发现我可以使用以下代码访问实际的异常详细信息:
import sys
import traceback
try:
1/0
除了:
exc_type,exc_value,exc_traceback = sys.exc_info()
traceback.print_exception(exc_type,exc_value,exc_traceback)
我想以某种方式获取字符串 print_exception()
throws to stdout,以便我可以记录。
要解答您的问题,您可以使用 print_exception()
获取字符串版本 traceback.format_exception()
功能。它将回溯消息作为字符串列表返回,而不是将其打印到stdout,因此您可以使用它来执行所需的操作。例如:
import sys
import traceback
try:
asdf
除了NameError:
exc_type,exc_value,exc_traceback = sys.exc_info()
lines = traceback.format_exception(exc_type,exc_value,exc_traceback)
print''.join('! !'+ line for line in line)#记录它或其他任何地方
显示:
!追溯(最近最近的电话):
!!文件< stdin>,第2行,< module>
!! NameError:name'asdf'未定义
但是,我一定会建议使用标准的Python日志记录模块,由rlotun建议。这不是最简单的设置,但它是非常可定制的。
How can I log an exception in Python?
I've looked at some options and found out I can access the actual exception details using this code:
import sys
import traceback
try:
1/0
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback)
I would like to somehow get the string print_exception()
throws to stdout so that I can log it.
To answer your question, you can get the string version of print_exception()
using the traceback.format_exception()
function. It returns the traceback message as a list of strings rather than printing it to stdout, so you can do what you want with it. For example:
import sys
import traceback
try:
asdf
except NameError:
exc_type, exc_value, exc_traceback = sys.exc_info()
lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
print ''.join('!! ' + line for line in lines) # Log it or whatever here
This displays:
!! Traceback (most recent call last):
!! File "<stdin>", line 2, in <module>
!! NameError: name 'asdf' is not defined
However, I'd definitely recommend using the standard Python logging module, as suggested by rlotun. It's not the easiest thing to set up, but it's very customizable.
这篇关于如何记录python异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!