简体   繁体   English

向 sys.excepthook 添加函数

[英]Adding function to sys.excepthook

Say I have something like this, which sends unhanded exceptions to logging.critical() :假设我有这样的事情,它向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

It works:有用:

import logging
logging.basicConfig()

register_handler()

undefined() # logs, then runs original excepthook

However if register_handler() is called multiple times, multiple error_catcher 's are called in a chain, and the logging message appears several times..但是,如果多次调用register_handler()error_catcher在链中调用多个error_catcher ,并且日志消息会出现多次。

I can think of a few ways, but none of them are particularly good (like checking if sys.excepthook is the error_catcher function, or using a "have_registered" attribute on the module to avoid double-registering)我能想到几个方法,但没有一个特别好(比如检查sys.excepthook是否是 error_catcher 函数,或者在模块上使用“have_registered”属性来避免重复注册)

Is there a recommended way of doing this?有推荐的方法吗?

You can just check if sys.excepthook is still built-in function before registering your handler:您可以在注册处理程序之前检查sys.excepthook是否仍然是内置函数:

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

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

Having a module-level "have the hook already been registered" variable seems like the simplest and most reliable way of doing this.拥有一个模块级别的“已经注册了钩子”变量似乎是最简单和最可靠的方法。

The other possible solutions would fall over in certain (rather obscure) circumstances - checking if the sys.excepthook is a builtin function will fail if an application registers a custom excepthook , storing the original excepthook at function-definition time will clobber subsequently registered excepthook functions.其他可能的解决方案在某些(相当模糊的)情况下会失败 - 如果应用程序注册了自定义的excepthook ,则检查sys.excepthook是否是内置函数将失败,在函数定义时存储原始的excepthook将破坏随后注册的 excepthook 函数.

import sys

_hook_registered = False

def register_handler(force = False):
    global _hook_registered

    if _hook_registered and not force:
        return

    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

    _hook_registered = True

If you make orig_excepthook an argument with a default value, the default value is fixed once at definition-time.如果使orig_excepthook成为具有默认值的参数,则默认值在定义时固定一次。 So repeated calls to register_handler will not change 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

import logging
logging.basicConfig()

register_handler()
register_handler()
register_handler()

undefined() 

produces only one call to log.critical .只产生一次对log.critical调用。

You should use sys.__excepthook__ [1].你应该使用sys.__excepthook__ [1]。
It is an object that contains the original values of sys.excepthook [2] at the start of the program.它是一个包含程序开始时sys.excepthook [2] 的原始值的对象。
ie; IE;

import sys
import logging

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

    sys.excepthook = error_catcher

Reference:参考:
1. https://docs.python.org/3/library/sys.html#sys. 1. https://docs.python.org/3/library/sys.html#sys。 excepthook 例外钩子
2. https://docs.python.org/3/library/sys.html#sys.excepthook 2. https://docs.python.org/3/library/sys.html#sys.excepthook

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM