我希望禁用在出现异常时打印出的堆栈跟踪。
每当代码调用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)
.exception
方法发送 exc_info=False
: 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}")
sys.excepthook
。 - Bakuriu