Using python’s logging module to log all exceptions and errors

It’s probably a bad idea to log any exception thrown within the program, since Python uses exceptions also for normal control flow.

Therefore you should only log uncaught exceptions. You can easily do this using a logger’s exception() method, once you have an exception object.

To handle all uncaught exceptions, you can either wrap your script’s entry point in a try...except block, or by installing a custom exception handler by re-assigning sys.excepthook():

import logging
import sys

logger = logging.getLogger('mylogger')
# Configure logger to write to a file...

def my_handler(type, value, tb):
    logger.exception("Uncaught exception: {0}".format(str(value)))

# Install exception handler
sys.excepthook = my_handler

# Run your main script here:
if __name__ == '__main__':
    main()

Leave a Comment