Skip to content

Instantly share code, notes, and snippets.

Embed
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.
Usage:
@log_exc
def fn():
# Logged and caught
raise Exception()
@log_exc(msg="Hello!")
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__)
@wraps(fn)
def inner(*args, **kwargs):
try:
return fn(*args, **kwargs)
except exc:
logger.exception(msg)
if reraise:
raise
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.