Skip to content

Instantly share code, notes, and snippets.

@Yavor-Ivanov
Created May 11, 2016 11:12
Show Gist options
  • Save Yavor-Ivanov/b1fb7a90e704df63977f9f6f14608ef8 to your computer and use it in GitHub Desktop.
Save Yavor-Ivanov/b1fb7a90e704df63977f9f6f14608ef8 to your computer and use it in GitHub Desktop.
A function logger decorator in Python. It logs the class, function name, argument list and argument values. You can use it to decorate single functions or classes.
import logging
import inspect
logging.basicConfig(level=logging.DEBUG)
def log(fn):
def logger(self=None, *a, **ka):
cls_name = self.__class__.__name__ if self else ''
argspec = inspect.getargspec(fn)
args = {name:a[idx] for idx, name in enumerate(argspec.args[1:])}
logging.info('Called %s.%s with arguments %s',
cls_name,
fn.__name__,
args)
if (self):
return fn(self, *a, **ka)
return fn(*a, **ka)
if not inspect.isclass(fn):
return logger
cls = fn
for attr in cls.__dict__:
if callable(getattr(cls, attr)):
setattr(cls, attr, log(getattr(cls, attr)))
return cls
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment