如何在Python中禁用堆栈跟踪

6
我希望禁用在出现异常时打印出的堆栈跟踪。

1
禁用堆栈跟踪没有安全原因。 - user395760
不那么重要的原因,所以我把它删除了。 - Adam Oren
可能是Python全局异常处理的重复问题。 - Amber
1
这个问题与安全无关。 - Adam Oren
1
我理解你的问题,但你不是第一个基于错误前提提出问题的人,更有益的做法是纠正这个假设。 - user395760
显示剩余3条评论
2个回答

2

每当代码调用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}")

1
我发现以下解决方案/解决方法:
sys.tracebacklimit = 0

1
请不要这样做。拥有回溯信息是一件好事(商标)。请参考https://dev59.com/imw15IYBdhLWcg3wcrhC和http://docs.python.org/3/library/logging.html#logging.Logger.exception,了解保持回溯信息私密的正确方法。 - bruno desthuilliers
1
你实际想要的是一个自定义的 sys.excepthook - Bakuriu
2
Bruno,你能否添加一个例子,展示如何在不记录堆栈跟踪的情况下记录异常?欢迎你将其作为回答添加到这个问题中。 - Adam Oren

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接