Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I log current line, and stack info with Python?

Tags:

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?

SOLVED

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'] 
like image 308
prosseek Avatar asked Feb 23 '11 15:02

prosseek


People also ask

What is current call stack in Python?

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.


2 Answers

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.

like image 133
Duncan Avatar answered Nov 11 '22 12:11

Duncan


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.

like image 27
Dunes Avatar answered Nov 11 '22 11:11

Dunes