Skip to content

Instantly share code, notes, and snippets.

@TRManderson
Created May 26, 2017 13:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TRManderson/7eb94b881d17e1a5f956b9c6ecb827e6 to your computer and use it in GitHub Desktop.
Save TRManderson/7eb94b881d17e1a5f956b9c6ecb827e6 to your computer and use it in GitHub Desktop.
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