My sys.excepthook dies painfully

Steven D'Aprano steve at
Wed Jul 23 09:14:27 CEST 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]")
mylogger.setLevel(logging.DEBUG)'started logging')

def my_error_handler(type, value, tb):
    msg = "Uncaught %s: %s" % (type, value)
    sys.__excepthook__(type, value, tb)  # print the traceback to stderr

# Install exception handler.'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/", line 28, in my_error_handler
AttributeError: 'NoneType' object has no attribute 'exception'

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

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

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


More information about the Python-list mailing list