Skip to content

Instantly share code, notes, and snippets.

@leo-pfeiffer
Last active July 9, 2021 08:25
Show Gist options
  • Save leo-pfeiffer/ecb910759c4d23232d0a7e01f54ab7dc to your computer and use it in GitHub Desktop.
Save leo-pfeiffer/ecb910759c4d23232d0a7e01f54ab7dc to your computer and use it in GitHub Desktop.
Logging decorator
"""
Simple logging decorator.
Usage:
@log()
def foo():
# raise an exception
return 1 / 0
By default, the exception is logged and then raised.
If you only want to log but suppress the exception,
pass `break_on_error=False` to the decorator:
@log(break_on_error=False)
def foo():
...
To get a specific logger, specify the `logger_name`
argument. Otherwise, this defaults to `__name__`.
@log(logger_name='my_special_logger')
def foo():
...
"""
import logging
from functools import partial, wraps
import traceback
def log(func=None, logger_name=None, break_on_error=True):
logger_name = logger_name or __name__
logger = logging.getLogger(logger_name)
if func is None:
return partial(log, break_on_error=break_on_error)
@wraps(func)
def auto_logger(*args, **kwargs):
try:
return func(*args, **kwargs)
except BaseException as be:
logger.exception(
f'Function {func.__name__} ////// BaseException: {be} ////// '
f'Traceback: {traceback.format_exc()}'
)
if break_on_error:
raise be
return auto_logger
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment