For tracing race conditions in the code I need to display the caller name and how long the operations take.
The code below outputs:
2018-02-06 19:00:11.418800: get_data() called by **wrappe**r() (0:00:00.001010)
test result: PASS
How can I make it output the caller name instead of the decorator function name e.g.:
2018-02-06 19:05:47.617679: get_data() called by **test_get_data**() (0:00:00.034116)
test result: PASS
The code:
from datetime import datetime
import time, inspect
class Timer():
def __init__(self):
self.time_start = datetime.now()
def stop(self):
return (datetime.now() - self.time_start)
class Test2Decorators():
def caller(callee):
def timer(callee):
def wrapper(*args, **kwargs):
get_data_timer = Timer()
result = callee(*args, **kwargs)
print ' (%s)' % get_data_timer.stop()
return result
return wrapper
@timer
def wrapper(*args, **kwargs):
curframe = inspect.currentframe()
calframe = inspect.getouterframes(curframe, 2)
print '%s: %s() called by %s()' % (datetime.now(), callee.__name__, calframe[1][3]),
return callee(*args, **kwargs)
return wrapper
@caller
def get_data(self, product_id = None, product_name = None):
return 'test result: PASS'
def test_get_data():
print class_inst.get_data('beer', '32445256')
time.sleep(1)
class_inst = Test2Decorators()
test_get_data()