Python 使用回溯记录异常,但不显示消息两次

Python logging exceptions with traceback, but without displaying messages twice

如果我运行下面的代码:

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

如果您这样调用 exception

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

那么您可以在初始行中获得异常 class 名称。

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