1import os 2import inspect 3 4 5def trace_function(function, log_calls, log_results, label=''): 6 def wrapper(*args, **kwargs): 7 kwarg_strs = ['{}={}'.format(k, v) for (k, v) in kwargs] 8 arg_str = ', '.join([str(a) for a in args] + kwarg_strs) 9 call_str = '{}({})'.format(function.func_name, arg_str) 10 11 # Perform the call itself, logging before, after, and anything thrown. 12 try: 13 if log_calls: 14 print '{}: Calling {}'.format(label, call_str) 15 res = function(*args, **kwargs) 16 if log_results: 17 print '{}: {} -> {}'.format(label, call_str, res) 18 return res 19 except Exception as ex: 20 if log_results: 21 print '{}: {} raised {}'.format(label, call_str, type(ex)) 22 raise ex 23 24 return wrapper 25 26 27def trace_object(obj, log_calls, log_results, label=''): 28 for name, member in inspect.getmembers(obj): 29 if inspect.ismethod(member): 30 # Skip meta-functions, decorate everything else 31 if not member.func_name.startswith('__'): 32 setattr(obj, name, trace_function(member, log_calls, 33 log_results, label)) 34 return obj 35