【发布时间】:2026-02-20 10:15:02
【问题描述】:
我正在用 Python 实现一个自定义处理程序。当然,我需要覆盖 emit(self, record) 来做到这一点。一个例子:
from logging import Handler, LogRecord
class FooHandler(Handler):
def emit(self, record: LogRecord):
# handler logic
如您所见,每次我使用Logger 实例记录某些内容时,这都会提供LogRecord 到emit 的方法。
我从 CPython 源代码中看到了 LogRecord 的当前实现,您也可以从 here 中看到它。
假设我有一个名为 logger 的 Logger 实例。稍后在代码中的某个地方,我会这样做:
# either this
logger.exception(Exception("foo"))
# it does not have to be an instance of Exception, it's for the sake of simplicity
# or this
logger.error("foo", exc_info=True)
# this also provides a stack trace on the console handler
由于@thebjorn 评论了traceback 模块,我想我可以解决这个问题。但是我现在有三个问题:
- 如何从
LogRecord实例中获取异常? - 如果我执行
logger.error("message", exc_info=True),那么我不会传递任何异常实例。在这种情况下,由于我没有任何异常实例,我该如何获取回溯?
提前致谢。
环境
- Python 3.5 及以上版本
【问题讨论】:
-
traceback模块..? -
实际上,
SteamHandler的实现给了我一些洞察力,但我仍然可能需要对handleError 进行解释。 -
@thebjorn,这就是我想要的。我不知道标准库中存在这样的东西。
标签: python logging python-logging