My sys.excepthook dies painfully
dieter
dieter at handshake.de
Thu Jul 24 01:36:05 EDT 2014
Steven D'Aprano <steve at pearwood.info> writes:
> I have some code which sets up a logger instance, then installs it as
> sys.excepthook to capture any uncaught exceptions:
>
>
>
> import logging
> import logging.handlers
> import sys
>
> FACILITY = logging.handlers.SysLogHandler.LOG_LOCAL6
> mylogger = logging.getLogger('spam')
> handler = logging.handlers.SysLogHandler(
> address='/dev/log', facility=FACILITY)
> formatter = logging.Formatter("%(levelname)s:%(message)s [%(module)s]")
> handler.setFormatter(formatter)
> mylogger.addHandler(handler)
> mylogger.setLevel(logging.DEBUG)
> mylogger.info('started logging')
>
> def my_error_handler(type, value, tb):
> msg = "Uncaught %s: %s" % (type, value)
> mylogger.exception(msg)
> sys.__excepthook__(type, value, tb) # print the traceback to stderr
>
> # Install exception handler.
> mylogger.info('installing error handler')
> sys.excepthook = my_error_handler
>
> foo # Die with uncaught NameError.
>
>
>
> If I run this code, the INFO logging messages are logged, but the
> exception is not. Instead it is printed to the console:
>
>
> Error in sys.excepthook:
> Traceback (most recent call last):
> File "/home/steve/mylogging.py", line 28, in my_error_handler
> mylogger.exception(msg)
> AttributeError: 'NoneType' object has no attribute 'exception'
This tells you that "mylogger" is "None".
This can happen during finalization. When the interpreter is shut down,
it unbinds all variables in a complex process (somewhere, there
is a description how it proceeds). Unbinding a variable effectively
means bindiung it to "None".
This would suggest that the finalization starts before the "excepthook"
has been executed. I would consider this a bug.
More information about the Python-list
mailing list