我想禁用在引发异常时打印的堆栈跟踪。
问问题
6391 次
2 回答
1
每当代码调用该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}")
于 2021-02-05T00:00:45.580 回答
0
环顾四周,我发现了以下解决方案/解决方法:
sys.tracebacklimit = 0
于 2013-04-22T17:15:09.053 回答