My sys.excepthook dies painfully

Steven D'Aprano steve at pearwood.info
Wed Jul 23 03:14:27 EDT 2014


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'

Original exception was:
Traceback (most recent call last):
  [...]
  File "/home/steve/mylogging.py", line 35, in <module>
    foo
NameError: name 'foo' is not defined



(I've trimmed out some of the traceback, because the details aren't 
relevant.)

Any ideas what I'm doing wrong? How does mylogger get set to None?



-- 
Steven



More information about the Python-list mailing list