Skip to content

Commit

Permalink
Merge 538006f into 171ea3d
Browse files Browse the repository at this point in the history
  • Loading branch information
Dogeek committed Aug 15, 2020
2 parents 171ea3d + 538006f commit cfd528b
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions reusables/log.py
Expand Up @@ -13,6 +13,7 @@
import sys
from logging.handlers import (RotatingFileHandler,
TimedRotatingFileHandler)
import traceback

from reusables.namespace import Namespace
from reusables.shared_variables import sizes
Expand Down Expand Up @@ -282,3 +283,58 @@ def get_registered_loggers(hide_children=False, hide_reusables=False):
if not (hide_reusables and "reusables" in logger)
and not (hide_children and "." in logger)]


def log_function(logger=None):
"""
Decorator that logs function calls with their arguments to the specified logger.
:param logger: logger to log function calls to, defaults to the root logger
:type logger: logging.Logger
"""
if logger is None:
logger = logging.getLogger()
def wrapper(func):
def decorated(*a, **kw):
nonlocal logger
args = list(zip(func.__code__.co_varnames, a))
kwargs = list(kw.items())
argslist = ', '.join('%s=%s' % i for i in args + kwargs)
logger.info('Calling %s with arguments %s', func.__name__, argslist)
return func(*a, **kw)
return decorated
return wrapper


def log_exceptions(logger=None, exceptions=None, suppress=False, with_traceback=False):
'''
Decorator that logs exceptions to a specific logger
:param logger: The logger to log the exceptions to, defaults to the root logger
:type logger: logging.Logger, optional
:param exceptions: Exceptions to catch, defaults to (Exception, )
:type exceptions: tuple<Exception>, optional
:param suppress: Whether or not to suppress logged exceptions, defaults to False
:type suppress: bool, optional
:param with_traceback: Whether or not to log the traceback as well, defaults to False
:type with_traceback: bool, optional
'''
if logger is None:
logger = logging.getLogger()
if exceptions is None:
exceptions = (Exception, )
def wrapper(func):
def decorated(*a, **kw):
nonlocal logger
nonlocal exceptions
nonlocal with_traceback

try:
return func(*a, **kw)
except exceptions as e:
logger.exception('%s: %s', e.__name__, str(e))
if with_traceback and e.__traceback__:
for line in traceback.format_tb(e.__traceback__):
logger.exception(line.replace('\n', ''))
if not suppress:
raise e
return decorated
return wrapper

0 comments on commit cfd528b

Please sign in to comment.