Skip to content

Instantly share code, notes, and snippets.

@kurtbrose
Created March 12, 2019 23:09
Show Gist options
  • Save kurtbrose/f7d6843ba28786275c0bb4f9df389b26 to your computer and use it in GitHub Desktop.
Save kurtbrose/f7d6843ba28786275c0bb4f9df389b26 to your computer and use it in GitHub Desktop.
quick method logging
import collections
import functools
def log_methods(cls):
def __init__(self, *a, **kw):
cls.__init__(self, *a, **kw)
self._log = collections.deque(maxlen=100)
def logit(method):
if not callable(method):
return method
@functools.wraps(method)
def g(self, *a, **kw):
self._log.append((method.__name__, a, kw))
return method(self, *a, **kw)
return g
cls_vars = {
key: logit(val) for key, val in cls.__dict__.items()
if not key.startswith('__') }
cls_vars['__init__'] = __init__
return type(cls.__name__ + "Logged", (cls,), cls_vars)
if __name__ == "__main__":
@log_methods
class T(object):
def __init__(self, a, b):
self.a, self.b = a, b
def foo(self, c, d):
pass
def bar(self, e):
pass
t = T(1, 2)
t.foo(3, 4)
t.bar(e=5)
print t._log
# deque([('foo', (3, 4), {}), ('bar', (), {'e': 5})], maxlen=100)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment