如何使用调试信息记录 Python 错误? [英] How do I log a Python error with debug information?
问题描述
我正在使用 logging.error
将 Python 异常消息打印到日志文件:
I am printing Python exception messages to a log file with logging.error
:
import logging
try:
1/0
except ZeroDivisionError as e:
logging.error(e) # ERROR:root:division by zero
是否可以打印有关异常和生成异常的代码的更多详细信息,而不仅仅是异常字符串?诸如行号或堆栈跟踪之类的东西会很棒.
Is it possible to print more detailed information about the exception and the code that generated it than just the exception string? Things like line numbers or stack traces would be great.
推荐答案
logger.exception
将在错误消息旁边输出堆栈跟踪.
logger.exception
will output a stack trace alongside the error message.
例如:
import logging
try:
1/0
except ZeroDivisionError:
logging.exception("message")
输出:
ERROR:root:message
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ZeroDivisionError: integer division or modulo by zero
@Paulo Cheque 注释,请注意,在 Python 3 中,您必须调用 logging.exception
方法就在 except
部分内.如果您在任意位置调用此方法,您可能会得到一个奇怪的异常.文档对此发出警告."
@Paulo Cheque notes, "be aware that in Python 3 you must call the logging.exception
method just inside the except
part. If you call this method in an arbitrary place you may get a bizarre exception. The docs alert about that."
这篇关于如何使用调试信息记录 Python 错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!