python - 如何在 python 的 if 语句中记录手动引发的异常

标签 python exception

简单地说,我有一段代码如下所示:

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/

相关文章:

java - Spring Framework 在 RuntimeException 中包装检查异常

python - 如何解决类型错误 : '<' not supported between instances of 'int' and 'str' ?

python - 检查 QMessageBox 中的哪个按钮被点击

python - Kivy 复选框在 ScrollView 中不起作用

python - 对于 Project Euler,C++ 似乎比 Python Ruby 慢得多

java - 返回响应实体中断流程

python - 什么是全局默认超时

exception - 在 Perl 6 中,如何打印可能在编译时抛出的异常类型?

java - 查找所有的 xpath 或 cssSelector 位置

oracle - 关于pl/sql异常的问题