记录Python异常的最佳方式 [英] Best way to log a Python exception
问题描述
try:
#coode在这里
除了异常,e:
logging.error(e)
要打印有关异常的更多信息和生成它的代码,而不仅仅是异常字符串?像线条或堆栈跟踪这样的事情会很好。
logger.exception
这样做。
例如:
import logging
try:
1/0
除了例外为e:
logging.exception(message)
输出:
错误:root:message
追溯(最近最近呼叫最后):
文件< stdin>,第2行,< module>
ZeroDivisionError:整数除数或模数为零
@Paulo Check 注意到,请注意,在Python 3中,您必须调用 logging.exception
方法只是在内部,除了
部分,如果你在任意的地方调用这个方法,你可能会得到一个奇怪的例外,文档警告这个。
I'm printing my exceptions to a log file currently with:
try:
# coode in here
except Exception, e:
logging.error(e)
Could I be printing more 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
does that.
For example:
import logging
try:
1/0
except Exception as e:
logging.exception("message")
Output:
ERROR:root:message
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ZeroDivisionError: integer division or modulo by zero
@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屋!