Logging uncaught exceptions in Python Logging uncaught exceptions in Python python python

Logging uncaught exceptions in Python


Here's a complete small example that also includes a few other tricks:

import sysimport logginglogger = logging.getLogger(__name__)handler = logging.StreamHandler(stream=sys.stdout)logger.addHandler(handler)def handle_exception(exc_type, exc_value, exc_traceback):    if issubclass(exc_type, KeyboardInterrupt):        sys.__excepthook__(exc_type, exc_value, exc_traceback)        return    logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))sys.excepthook = handle_exceptionif __name__ == "__main__":    raise RuntimeError("Test unhandled")
  • Ignore KeyboardInterrupt so a console python program can exit with Ctrl + C.

  • Rely entirely on python's logging module for formatting the exception.

  • Use a custom logger with an example handler. This one changes the unhandled exception to go to stdout rather than stderr, but you could add all sorts of handlers in this same style to the logger object.


As Ned pointed out, sys.excepthook is invoked every time an exception is raised and uncaught. The practical implication of this is that in your code you can override the default behavior of sys.excepthook to do whatever you want (including using logging.exception).

As a straw man example:

import sysdef foo(exctype, value, tb):    print('My Error Information')    print('Type:', exctype)    print('Value:', value)    print('Traceback:', tb)

Override sys.excepthook:

>>> sys.excepthook = foo

Commit obvious syntax error (leave out the colon) and get back custom error information:

>>> def bar(a, b)My Error InformationType: <type 'exceptions.SyntaxError'>Value: invalid syntax (<stdin>, line 1)Traceback: None

For more information about sys.excepthook, read the docs.


The method sys.excepthook will be invoked if an exception is uncaught: http://docs.python.org/library/sys.html#sys.excepthook

When an exception is raised and uncaught, the interpreter calls sys.excepthook with three arguments, the exception class, exception instance, and a traceback object. In an interactive session this happens just before control is returned to the prompt; in a Python program this happens just before the program exits. The handling of such top-level exceptions can be customized by assigning another three-argument function to sys.excepthook.