By prosseek

2011-02-23 15:34:53 8 Comments

I have logging function as follows.

    filename = fileName,
    format = "%(levelname) -10s %(asctime)s %(message)s",
    level = logging.DEBUG

def printinfo(string):
    if DEBUG:

def printerror(string):
    if DEBUG:
    print string

I need to login the line number, stack information. For example:

1: def hello():
2:    goodbye()
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)
    if LOG:

gives me this info which is exactly what I need.

DEBUG      2011-02-23 10:09:13,500 [
  '  File "/", line 553, in <module>\n    runUnitTest(COVERAGE, PROFILE)\n', 
  '  File "/", line 411, in runUnitTest\n    printinfo(string)\n']


@barny 2019-03-11 17:18:35

This is based on @mouad's answer but made more useful (IMO) by including at each level the filename (but not its full path) and line number of the call stack, and by leaving the stack in most-recently-called-from (i.e. NOT reversed) order because that's the way I want to read it :-)

Each entry has file:line:func() which is the same sequence as the normal stacktrace, but all on the same line so much more compact.

import inspect

def callers(self):
    caller_list = []
    frame = inspect.currentframe()
    while frame.f_back:
        frame = frame.f_back
    callers =  ' <= '.join(caller_list)
    return callers

You may need to add an extra f_back if you have any intervening calls to produce the log text.

        frame = inspect.currentframe().f_back

Produces output like this: <= <= <= <= <=

I only need this stacktrace in two key functions, so I add the output of callers into the text in the logger.debug() call, like htis:

logger.debug("\nWIRE: justdoit request -----\n"+callers()+"\n\n")

@bsimmons 2014-10-31 19:33:39

Late answer, but oh well.

Another solution is that you can create your own formatter with a filter as specified in the docs here. This is a really great feature as you now no longer have to use a helper function (and have to put the helper function everywhere you want the stack trace). Instead, a custom formatted implements it directly into the logs themselves.

import logging
class ContextFilter(logging.Filter):
    def __init__(self, trim_amount)
        self.trim_amount = trim_amount
    def filter(self, record):
        import traceback
        record.stack = ''.join(
            str(row) for row in traceback.format_stack()[:-self.trim_amount]
        return True

# Now you can create the logger and apply the filter.
logger = logging.getLogger(__name__)

# And then you can directly implement a stack trace in the formatter.    
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s \n %(stack)s')

Note: In the above code I trim the last 5 stack frames. This is just for convenience and so that we don't show stack frames from the python logging package itself.(It also might have to be adjusted for different versions of the logging package)

@ncoghlan 2011-02-23 22:40:08

As of Python 3.2, this can be simplified to passing the stack_info=True flag to the logging calls. However, you'll need to use one of the above answers for any earlier version.

@Will S 2015-07-24 09:43:17

The docs are kind of wordy with regards to this. I had missed that, thanks!

@mouad 2011-02-23 16:06:33

Here is an example that i hope it can help you:

import inspect
import logging

    format = "%(levelname) -10s %(asctime)s %(message)s",
    level = logging.DEBUG

def test():

    caller_list = []
    frame = inspect.currentframe()
    this_frame = frame  # Save current frame.

    while frame.f_back:
        frame = frame.f_back

    caller_line = this_frame.f_back.f_lineno
    callers =  '/'.join(reversed(caller_list))'Line {0} : {1}'.format(caller_line, callers))

def foo():

def bar():



INFO       2011-02-23 17:03:26,426 Line 28 : bar()/foo()/test()

@Duncan 2011-02-23 16:01:06

Current function name, module and line number you can do simply by changing your format string to include them.

    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.

@Scott Stafford 2015-11-25 18:28:06

@Erik Aronesty 2016-02-26 20:07:52

hard part is getting the stack_trace[:-1]

@Duncan 2016-02-28 20:03:34

@ErikAronesty, yes and that was already sufficiently covered by other answers when I posted, so I didn't include it in mine.

@Dunes 2011-02-23 15:47:33

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.

@ShadowRanger 2016-03-04 20:43:13

Instead of doing stack_trace[:-1] (which means it needs to format one frame more than you use, then slice the result), couldn't you do: frame = inspect.currentframe(1) so you get the stack without the top layer, so format_stack doesn't need to process it, and the return from format_stack requires no manipulation?

@yanjost 2011-02-23 15:50:24

Look at traceback module

>>> import traceback
>>> def test():
>>>     print "/".join( str(x[2]) for x in traceback.extract_stack() )
>>> def main():
>>>     test()
>>> main()

@Daniel Roseman 2011-02-23 15:46:44

Use the traceback module.


Related Questions

Sponsored Content

28 Answered Questions

[SOLVED] How do I concatenate two lists in Python?

10 Answered Questions

14 Answered Questions

[SOLVED] How do I get a substring of a string in Python?

55 Answered Questions

[SOLVED] How to upgrade all Python packages with pip?

  • 2010-04-27 09:23:25
  • thedjpetersen
  • 1230707 View
  • 2071 Score
  • 55 Answer
  • Tags:   python pip

42 Answered Questions

[SOLVED] How to get the current time in Python

  • 2009-01-06 04:54:23
  • user46646
  • 3339576 View
  • 2941 Score
  • 42 Answer
  • Tags:   python datetime time

25 Answered Questions

[SOLVED] How can I safely create a nested directory?

28 Answered Questions

[SOLVED] How to read a file line-by-line into a list?

16 Answered Questions

[SOLVED] How do I copy a file in Python?

10 Answered Questions

[SOLVED] How can I do a line break (line continuation) in Python?

2 Answered Questions

[SOLVED] Python logging typeerror

Sponsored Content