I have logging function as follows.
logging.basicConfig( filename = fileName, format = "%(levelname) -10s %(asctime)s %(message)s", level = logging.DEBUG ) def printinfo(string): if DEBUG: logging.info(string) def printerror(string): if DEBUG: logging.error(string) print string
I need to login the line number, stack information. For example:
1: def hello(): 2: goodbye() 3: 4: def goodbye(): 5: printinfo() ---> Line 5: goodbye()/hello()
How can I do this with Python?
def printinfo(string): if DEBUG: frame = inspect.currentframe() stack_trace = traceback.format_stack(frame) logging.debug(stack_trace[:-1]) if LOG: logging.info(string)
gives me this info which is exactly what I need.
DEBUG 2011-02-23 10:09:13,500 [ ' File "/abc.py", line 553, in <module>\n runUnitTest(COVERAGE, PROFILE)\n', ' File "/abc.py", line 411, in runUnitTest\n printinfo(string)\n']
The Python interpreter uses a call stack to run a Python program. When a function is called in Python, a new frame is pushed onto the call stack for its local execution, and every time a function call returns, its frame is popped off the call stack.
Current function name, module and line number you can do simply by changing your format string to include them.
logging.basicConfig( filename = fileName, format = "%(levelname) -10s %(asctime)s %(module)s:%(lineno)s %(funcName)s %(message)s", level = logging.DEBUG )
Most people only want the stack when logging an exception, and the logging module does that automatically if you call logging.exception()
. If you really want stack information at other times then you will need to use the traceback module for extract the additional information you need.
import inspect import traceback def method(): frame = inspect.currentframe() stack_trace = traceback.format_stack(frame) print ''.join(stack_trace)
Use stack_trace[:-1] to avoid including method/printinfo in the stack trace.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With