向sys.excepthook添加函数 [英] Adding function to sys.excepthook
问题描述
说我有这样的东西,发送unhanded例外到 logging.critical()
:
Say I have something like this, which sends unhanded exceptions to 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
它的工作原理:
import logging
logging.basicConfig()
register_handler()
undefined() # logs, then runs original excepthook
但是如果 register_handler()
次,多个 error_catcher
在链中调用,并且日志消息出现几次。
However if register_handler()
is called multiple times, multiple error_catcher
's are called in a chain, and the logging message appears several times..
可以想到几种方法,但没有一个是特别好的(如检查 sys.excepthook
是error_catcher函数,还是使用模块上的have_registered属性避免重复注册)
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)
是否有推荐的方法?
推荐答案
有一个模块级的已经挂钩已经注册变量看起来像这样做最简单和最可靠的方法。
Having a module-level "have the hook already been registered" variable seems like the simplest and most reliable way of doing this.
其他可能的解决方案在某些(相当晦涩的)情况下会发生崩溃 -
检查 sys.excepthook
是否是内置函数将失败,如果应用程序注册自定义 excepthook
,在函数定义时存储原始 excepthook
将会随后注册excepthook函数。
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.
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
这篇关于向sys.excepthook添加函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!