如何在Python的__exit__方法中生成异常的合理文本日志?
解决__exit__方法中记录退出异常原因的问题
你遇到的问题是因为__exit__方法接收的traceback参数是原生traceback对象,而非TracebackException实例,所以无法直接调用format_exception_only方法。以下是两种可行的解决方案:
方案一:直接利用异常类型和异常值参数
__exit__的前两个参数exception_type(异常类型)和exception_value(异常实例)已经包含了你需要的信息,直接拼接即可生成目标日志:
def __exit__(self, exception_type, exception_value, traceback): # 其他逻辑 if exception_type is not None: exit_msg = f'Exiting due to {exception_type.__name__}: {exception_value}' else: exit_msg = 'Exiting normally' self.log_file.write(exit_msg) self.log_file.close()
当发生除零错误时,会输出Exiting due to ZeroDivisionError: Division by zero,完全符合你的需求。
方案二:使用traceback模块的format_exception_only函数
如果你更倾向于用traceback模块的工具函数,需要将exception_type和exception_value传入traceback.format_exception_only,而非直接使用traceback参数:
import traceback def __exit__(self, exception_type, exception_value, traceback): # 其他逻辑 if exception_type is not None: # format_exception_only返回列表,取第一个元素并去除换行符 error_detail = traceback.format_exception_only(exception_type, exception_value)[0].strip() exit_msg = f'Exiting due to {error_detail}' else: exit_msg = 'Exiting normally' self.log_file.write(exit_msg) self.log_file.close()
这个方法会生成和方案一完全一致的输出,适合习惯使用traceback模块API的场景。
需要注意:当with块正常执行无异常时,exception_type、exception_value和traceback都会是None,所以要先判断是否存在异常,再生成对应退出消息。
内容的提问来源于stack exchange,提问作者pythonmegapixel
相关产品推荐
相关产品推荐

