Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Handy decorator for exception logging using `logging`
import logger
from functools import wraps
def log_exc(fn=None, reraise=None, msg=None, exc=None, logger=None):
Decorator to log exceptions in a function.
def fn():
# Logged and caught
raise Exception()
def fn():
# Logged and caught with message "Hello!"
raise Exception()
:param reraise: Reraise the exception once caught
:param msg: Message to log with, default is "An error occurred!"
:param exc: Exception class to catch, default is `Exception`
:param logger: `logging.Logger` to use, default is based on fn.__qualname__.
optional_args = [
reraise, msg, exc, logger
if any(optional_args) and fn is None:
return lambda fn: log_exc(fn, reraise=reraise, msg=msg, exc=exc, logger=logger)
elif fn is None:
raise ValueError("No function and no configuration provided")
reraise = reraise or False
msg = msg or "An error occurred!"
exc = exc or Exception
logger = logger or logging.getLogger(fn.__qualname__)
def inner(*args, **kwargs):
return fn(*args, **kwargs)
except exc:
if reraise:
return inner
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.