Global exception handler for Python scripts

Recently I write more and more Python scripts to automate various tasks. Since they are running on schedule, I typically don’t see any output from them. Because I like to know what happened, I’m using loguru to log messages during execution.

Loguru is simple but powerful. The problem I had was that some errors were not handled. Loguru is not handling errors by default, try/except is handling exceptions I was aware of. What if I want to handle exception I was not expecting?

Global exception handler

In my automatization scripts, I started to use global exception handler. The implementation is rather simple:

import sys, traceback
from loguru import logger

def exception_handler(exctype, value, tb):
    logger.error(exctype)
    logger.error(value)
    logger.error(traceback.extract_tb(tb))

sys.excepthook = exception_handler

The exception handler function is taking care of proper logging – It contains the information that was useful for me. Especially “extract_tb”. It shows the exact stack trace, code lines, and files the exception is involved with.

Since I’m using not only display messages when logging, all my logs are also stored in the file. Refer to the Loguru documentation for details.

Such an approach gives me full coverage of the unexpected exceptions in the whole script. I know – this function is not able to recover from an exception, but at least I know what happened 🙂