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
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..
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)
Is there a recommended way of doing this?