简单地说,我有一段代码如下所示:
if some_condition_that_evals_to_True:
raise ValueError("Error message")
我想做的是插入一个记录整个异常的日志记录语句,但这样做只会保存记录器消息:
if some_condition_that_evals_to_True:
logger.error("Logged error message")
raise ValueError("Error message")
有人知道如何保存包括 ValueError 在内的整个错误消息吗?
编辑:
以下是我正在尝试重新创建的内容:
if some_condition_that_evals_to_True:
try:
raise ValueError("Error with value")
except ValueError:
logger.exception("Logging Error with Value")
raise
但这似乎是获得我想要的行为的迂回方式,所以换一种方式来表达我的问题:是否有更优雅的方式获得与上述代码块相同的行为?
最佳答案
在使用 logging module 时尝试使用 stack_info
关键字参数:
import logging
logging.basicConfig(filename='example.log',level=logging.DEBUG)
if True:
logging.error('Error Message', stack_info=True)
raise ValueError('Custom Error Message')
运行它会显示以下内容:
J:\>python log_stack.py
Traceback (most recent call last):
File "log_stack.py", line 5, in <module>
raise ValueError('Custom Error Message')
ValueError: Custom Error Message
J:\>more example.log
ERROR:root:Error Message
Stack (most recent call last):
File "log_stack.py", line 4, in <module>
logging.error('Error Message', stack_info=True)
关于python - 如何在 python 的 if 语句中记录手动引发的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44059192/