Skip to main content
 首页 » 编程设计

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

2024年10月01日998°冷暖

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

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)