在python中使用回溯记录异常 [英] Log exception with traceback in python
本文介绍了在python中使用回溯记录异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何记录 Python 错误?
How can I log my Python errors?
try:
do_something()
except:
# How can I log my exception here, complete with its traceback?
推荐答案
使用 logging.exception
来自 except:
处理程序/块,用于记录当前异常以及跟踪信息,并附加一条消息.
Use logging.exception
from within the except:
handler/block to log the current exception along with the trace information, prepended with a message.
import logging
LOG_FILENAME = '/tmp/logging_example.out'
logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG)
logging.debug('This message should go to the log file')
try:
run_my_stuff()
except:
logging.exception('Got exception on main handler')
raise
现在查看日志文件,/tmp/logging_example.out
:
DEBUG:root:This message should go to the log file
ERROR:root:Got exception on main handler
Traceback (most recent call last):
File "/tmp/teste.py", line 9, in <module>
run_my_stuff()
NameError: name 'run_my_stuff' is not defined
这篇关于在python中使用回溯记录异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文