Adding function to sys.excepthook

前端 未结 5 686
不知归路
不知归路 2021-01-13 12:02

Say I have something like this, which sends unhanded exceptions to logging.critical():

import sys

def register_handler():
    orig_excepthook =         


        
5条回答
  •  一个人的身影
    2021-01-13 12:59

    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.

    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
    

提交回复
热议问题