小编典典

在python中使用回溯记录异常

all

如何记录我的 Python 错误?

try:
    do_something()
except:
    # How can I log my exception here, complete with its traceback?

阅读 76

收藏
2022-07-02

共1个答案

小编典典

logging.exception在处理程序/块中使用except:以记录当前异常以及跟踪信息,并以消息开头。

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
2022-07-02