将函数添加到系统异常

2024-04-27 21:37:24 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有这样的东西,它向logging.critical()发送未经处理的异常:

import sys

def register_handler():
    orig_excepthook = sys.excepthook

    def error_catcher(*exc_info):
        import logging
        log = logging.getLogger(__name__)
        log.critical("Unhandled exception", exc_info=exc_info)
        orig_excepthook(*exc_info)

    sys.excepthook = error_catcher

它起作用:

^{pr2}$

但是,如果多次调用register_handler(),则在一个链中调用多个{},并且日志消息会出现几次。。在

我可以想出几种方法,但是没有一种方法特别好(比如检查sys.excepthook是否是错误捕获器函数,或者在模块上使用“have_registered”属性以避免重复注册)

有没有推荐的方法?在


Tags: 方法importinforegisterlogloggingdefsys
3条回答

如果使orig_excepthook成为一个具有默认值的参数,则默认值在定义时固定一次。因此,对register_handler的重复调用不会改变orig_excepthook。在

import sys

def register_handler(orig_excepthook=sys.excepthook):
    def error_catcher(*exc_info):
        import logging
        log = logging.getLogger(__name__)
        log.critical("Unhandled exception", exc_info=exc_info)
        orig_excepthook(*exc_info)
    sys.excepthook = error_catcher

^{pr2}$

只生成一个对log.critical的调用。在

如果将问题中的代码放入模块中,可以多次导入,但只会第一次执行。在

在注册处理程序之前,您只需检查sys.excepthook是否仍然是内置函数:

>>> import sys, types
>>> isinstance(sys.excepthook, types.BuiltinFunctionType)
True
>>> sys.excepthook = lambda x: x
>>> isinstance(sys.excepthook, types.BuiltinFunctionType)
False

相关问题 更多 >