如何记录Python异常?
try:
do_something()
except:
# How can I log my exception here, complete with its traceback?
如何记录Python异常?
try:
do_something()
except:
# How can I log my exception here, complete with its traceback?
当前回答
使用日志记录。Exception:处理程序/块中的异常,以记录当前异常和跟踪信息,并添加一条消息。
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
其他回答
使用exc_info选项可能更好,保留警告或错误标题:
try:
# coode in here
except Exception as e:
logging.error(e, exc_info=True)
下面是一个简单的例子,摘自python 2.6文档:
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')
下面是一个使用sys.excepthook的版本
import traceback
import sys
logger = logging.getLogger()
def handle_excepthook(type, message, stack):
logger.error(f'An unhandled exception occured: {message}. Traceback: {traceback.format_tb(stack)}')
sys.excepthook = handle_excepthook
使用日志记录。Exception:处理程序/块中的异常,以记录当前异常和跟踪信息,并添加一条消息。
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
我要找的是:
import sys
import traceback
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback_in_var = traceback.format_tb(exc_traceback)
看到的:
https://docs.python.org/3/library/traceback.html