何时需要将异常对象传递给 Logger.exception



什么时候需要将异常对象传递给Logger.exception

对我来说,以下模式更好,因为我可以编写自定义消息:

try:
my_function()
except Exception as e:
logger.exception('custom message')

有没有理由这样做:

try:
my_function()
except Exception as e:
logger.exception(e)  # the difference is passing the exception object to the log

不传递会丢失哪些信息?

在您在此处显示的特定内容中,不会丢失信息。日志记录模块使用sys.exc_info()来获取有关当前异常的信息,因此只要您位于该异常块内,就无需传入异常。只有在以下方案中异常对象不是当前异常的情况下才需要它,例如:

import logging
try:
some_func()
except ValueError as e:
# handle ValueError here
err = e
except OtherException as e:
# handle OtherException here
err = e
except Exception as e:
# handle Exception here
err = e
if err:
logging.exception(err) # here we need to pass the exception object expicitely

可能值得注意的是,您也可以同时执行这两项操作,传入异常并使用logging.exception("your message", exc_info=e)发送消息。

logging.exception只是logging.error的一个方便的包装器,实际上非常简单地实现如下:(在cpython中(

def exception(self, msg, *args, exc_info=True, **kwargs):
self.log(ERROR, msg, *args, exc_info=exc_info, **kwargs)

最新更新