我可能有所疏漏,但调用logger.exception(e)
已经添加了堆栈跟踪和错误消息。
(而logger.error(e)
只显示消息)
请参考这个POC脚本:
import logging
import logging.config
logging.config.dictConfig({
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'logfileFormat': {
'format': '%(asctime)s %(name)-12s: %(levelname)s %(message)s'
}
},
'handlers': {
'logfile': {
'level': 'INFO',
'formatter': 'logfileFormat',
'class': 'logging.StreamHandler',
'stream': 'ext://sys.stdout',
},
},
'loggers': {
'': {
'handlers': ['logfile'],
'level': 'INFO',
'propagate': False
},
}
})
def foo():
logging.info("Normal stuff")
logging.warning("More stuff")
try:
raise Exception("Something something, Exception")
except Exception as e:
logging.exception(e)
try:
raise Exception("The stacktrace of this is surpressed")
except Exception as e:
logging.error(e)
logging.info("More normal stuff")
foo()
这将导致以下输出:
2020-07-26 20:54:27,621 root : INFO Normal stuff
2020-07-26 20:54:27,621 root : WARNING More stuff
2020-07-26 20:54:27,621 root : ERROR Something something, Exception
Traceback (most recent call last):
File "sol.py", line 34, in foo
raise Exception("Something something, Exception")
Exception: Something something, Exception
2020-07-26 20:54:27,622 root : ERROR The stacktrace of this is surpressed
2020-07-26 20:54:27,622 root : INFO More normal stuff
我看不出您现有的
格式化程序需要进行何种更改。
如果您想要
缩进或以其他方式
格式化堆栈跟踪,请参见
this SO answer,了解如何创建一个
自定义格式化程序。
logger.exception("Error occurred: %s", e)
这样的东西不够用吗? - wowkin2