I'm implementing logging function in a static period, and getting id to identify where the function is called is necessary for this. Currently the id is computed with serialization of 'inspect.stack()[1][1:]' by 'pickle' and I have created below python script for testing this feature. I'm currently using 'inspect' module but it returns only filename, linenumber, source at that line.
import inspect
import hashlib
def loginfo_throttle():
frame = inspect.stack()[1][0]
print('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
print(hashlib.md5(pickle.dumps(inspect.stack()[1][1:])).hexdigest())
print(inspect.getframeinfo(frame))
print('<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<')
def main():
loginfo_throttle();loginfo_throttle()
loginfo_throttle()
if __name__ == '__main__':
main()
The output is as below, and the first and second output is exactly same and this is the problem.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
9ab15e3e3d106afca16e4155ac571152
Traceback(filename='spam.py', lineno=20, function='main', code_context=[' loginfo_throttle();loginfo_throttle()\n'], index=0)
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
9ab15e3e3d106afca16e4155ac571152
Traceback(filename='spam.py', lineno=20, function='main', code_context=[' loginfo_throttle();loginfo_throttle()\n'], index=0)
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
2d63d9b94b68ba14989ffebed0b70ab2
Traceback(filename='spam.py', lineno=21, function='main', code_context=[' loginfo_throttle()\n'], index=0)
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Update
What I'd like to do in actual is as below, so distinguishing functions in same line using the called time is difficult.
import inspect
import pickle
import time
class LoggingThrottle(object):
time_table = {}
def __call__(self, period, msg):
id = pickle.dumps(inspect.stack()[1][1:])
now = time.time()
last_time = self.time_table.get(id)
if (last_time is None) or ((now - last_time) > period):
print(msg)
self.time_table[id] = now
logging_throttle = LoggingThrottle()
def main():
for i in xrange(1000):
logging_throttle(3, 'foo'); logging_throttle(3, 'spam')
logging_throttle(3, 'bar')
time.sleep(0.1)
if __name__ == '__main__':
main()
This outputs only 'foo' and 'bar'.
foo
bar
foo
bar