The following function that reports the “current” line-number (and time) which I would like to call from within other functions when a runtime Exception occurs.
Understandably the line number returned always relates to the position of getframeinfo within the gTime() function itself, i.e. it’s static.
I simply want the gTime() functionality whenever I require the line.num/time data without directly adding the (long) gTime code into each position where it’s required within the main code body. I guess some sort of command sequence alias is what I am really looking for to substitute the code within my gTime() function – but can’t find any solution to my problem.
The standard ‘logger’ module won’t work reliably within my multi-threaded application so I am resorting to a hand-rolled solution.
from inspect import currentframe, getframeinfo
from datetime import datetime
def gTime():
position = "%s [%s] - " % (str(datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f").rstrip('0')),getframeinfo(currentframe()).lineno)
return position
print gTime()
If you can’t use
logging, I’d suggest using as much as you can of its internals or at least learning from them; see http://hg.python.org/cpython/file/tip/Lib/logging/__init__.py.In particular,
logging.currentframecan be used to get an enclosing frame: