【问题标题】:Python logging exceptions with traceback, but without displaying messages twice带有回溯的 Python 记录异常,但不显示消息两次
【发布时间】:2016-06-03 12:42:57
【问题描述】:

如果我运行以下代码:

import logging
logger = logging.getLogger('creator')
try:
    # some stuff
except Exception as exception:
    logger.exception(exception)

我在屏幕上得到以下输出:

creator     : ERROR    division by zero
Traceback (most recent call last):
  File "/graph_creator.py", line 21, in run
    1/0
ZeroDivisionError: division by zero

有没有办法得到这样的输出?

creator     : ERROR    ZeroDivisionError: division by zero
Traceback (most recent call last):
  File "/graph_creator.py", line 21, in run
    1/0

当然,我可以得到这个(但我不喜欢它):

creator     : ERROR    Сaught exception (and etc...)
Traceback (most recent call last):
  File "/graph_creator.py", line 21, in run
    1/0
ZeroDivisionError: division by zero

【问题讨论】:

  • 看到您的评论。您需要采用自定义的Formatter 方法。

标签: python exception logging exception-handling output


【解决方案1】:

如果你这样称呼exception

logger.exception('%s: %s', exception.__class__.__name__, exception)

那么你可以在第一行得到异常类名。

如果您需要更精确的更改,您可以使用自定义的Formatter 子类,它可以完全按照您的喜好格式化。这将需要覆盖 format_exception 以更改回溯的格式。

【讨论】:

  • 在我的日志文件中,我得到了两次“ZeroDivisionError:除以零”,在回溯之上和之后,我需要在上面
猜你喜欢
  • 1970-01-01
  • 2020-11-03
  • 2010-12-03
  • 2010-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-16
  • 2020-01-02
相关资源
最近更新 更多