【问题标题】:How to disable stack trace in python如何在python中禁用堆栈跟踪
【发布时间】:2013-04-22 17:15:09
【问题描述】:

我想禁用在引发异常时打印的堆栈跟踪。

【问题讨论】:

  • 禁用堆栈跟踪没有安全原因。
  • 原因不是很重要,所以我删除了它。
  • 这个问题与安全无关
  • 我明白这一点,但您不会是第一个基于错误前提提出问题的人,并且会从纠正该假设中受益更多。

标签: python logging stack-trace


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    环顾四周,我发现了以下解决方案/解决方法:

    sys.tracebacklimit = 0

    【讨论】:

    猜你喜欢
    • 2016-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-24
    • 1970-01-01
    • 2019-06-16
    • 2019-10-02
    相关资源
    最近更新 更多