我想禁用在引发异常时打印的堆栈跟踪。
答案 0 :(得分:0)
环顾四周,我找到了以下解决方案/解决方法:
sys.tracebacklimit = 0
答案 1 :(得分:0)
每当代码调用 logger.exception
方法时,都会自动打印堆栈跟踪。
这是因为 exc_info
方法的 .exception
参数的默认值为 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}")