« Back to Index

Python Exception Logging Decorator

View original Gist on GitHub

exception-logging-decorator.py

import logging

def exception(func):
    def wrapper(n):
        try:
            return func(n)
        except Exception as err:
            logging.error("Error: %s", err)
            raise
    return wrapper

@exception
def cause_an_error(n):
    return 1 / n

if __name__ == "__main__":
    try:
        result = cause_an_error(1) # change to zero to see the failure
        print(result)
    except Exception as err:
        print(err)