Say I have something like this that 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
Works:
import logging logging.basicConfig() register_handler() undefined()
However, if register_handler()
is called multiple times, several error_catcher
is called in the chain, and the registration message appears several times.
I can come up with several methods, but none of them are particularly good (for example, if the sys.excepthook
function is an error_catcher function or uses the has_registered attribute on a module to avoid double registration)
Is there a recommended way to do this?
source share