Adding function to sys.excepthook

前端 未结 5 653
不知归路
不知归路 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 13:09

    If you make orig_excepthook an argument with a default value, the default value is fixed once at definition-time. So repeated calls to register_handler will not change 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.

提交回复
热议问题