Skip to content
Browse files

a very simple instrumentation instrument

  • Loading branch information
stnbu committed Sep 28, 2018
1 parent 4a955cc commit 4afac5fe3295188a536e7bd8877c079f63a7debe
Showing with 53 additions and 0 deletions.
  1. +53 −0
@@ -0,0 +1,53 @@
import re
import os
import types
import inspect
from functools import wraps
import logging

def instrument_function(obj):

def wrapper(*args, **kwargs):
result = obj(*args, **kwargs)
logging.error('called {function} with args {args}, {kwargs} returned {result}'.format(
return result
return wrapper

def instrument_class(decorator):

def decorate(cls):
for attr in cls.__dict__: # there's propably a better way to do this
if callable(getattr(cls, attr)):
setattr(cls, attr, decorator(getattr(cls, attr)))
return cls
return decorate

def instrument_this_module():
"""When called at the bottom of a module, monkeypatch module to instrument functions, classes
frame = inspect.stack()[1]
module = inspect.getmodule(frame[0])
# this is silly, but it allows us to include __main__ (when module is executed)
module_name = re.sub('\.py[co]?$', '', os.path.basename(module.__file__))
# monkeypatch the module...
for name, obj in module.__dict__.items():
if isinstance(obj, types.FunctionType):
module.__dict__[name] = instrument_function(obj)
elif isinstance(obj, type):

# @instrument
# def myfun(arg1, arg2, kwarg1=None):
# return id(arg1) + id(arg2) + id(kwarg1)
# myfun(1, 2, kwarg1=3)

0 comments on commit 4afac5f

Please sign in to comment.