如果我运行以下代码:
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)
然后,您可以在初始行中获取异常类名。
如果需要更精确的更改,可以使用自定义Formatter
子类,该子类可以完全按照您喜欢的方式格式化内容。这将需要覆盖format_exception
以更改回溯的格式。