2

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()
Tony
  • 7,767
  • 2
  • 22
  • 51
  • 1
    Possible duplicate of [Getting the caller function name inside another function in Python?](https://stackoverflow.com/questions/900392/getting-the-caller-function-name-inside-another-function-in-python) – Dr Xorile Feb 06 '18 at 18:16

1 Answers1

0

I just figured this out this way:

from datetime import datetime
import inspect
import time

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()' % inspect.stack()[1][3],
                print ' (%s)' % get_data_timer.stop()
                return result
            return wrapper

        @timer
        def wrapper(*args, **kwargs):
            print '%s: %s() called by' % (datetime.now(), callee.__name__),
            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():
    while True:
        print class_inst.get_data('beer', '32445256')
        time.sleep(1)

class_inst = Test2Decorators()
test_get_data()
Tony
  • 7,767
  • 2
  • 22
  • 51