每当代码调用logger.exception 方法时,就会自动打印堆栈跟踪。
这是因为.exception方法的exc_info参数的默认值为True。
查看源代码:
def exception(msg, *args, exc_info=True, **kwargs):
"""
Log a message with severity 'ERROR' on the root logger, with exception
information. If the logger has no handlers, basicConfig() is called to add
a console handler with a pre-defined format.
"""
error(msg, *args, exc_info=exc_info, **kwargs)
为了防止这种情况,您可以像这样将exc_info=False 发送到.exception 方法:
try:
raise Exception("Huston we have a problem!")
except Exception as ex:
logger.exception(f"Looks like they have a problem: {ex}", exc_info=False)
虽然这似乎可行,但强制用户每次使用该方法时都写exc_info=False 是不好的。因此,为了减轻程序员的负担,您可以修改 .exception 方法,使其像普通的 .error 方法一样运行,如下所示:
# somewhere in the start of your program
# money patch the .exception method
logger.exception = logger.error
try:
raise Exception("Huston we have a problem!")
except Exception as ex:
logger.exception(f"Looks like they have a problem: {ex}")