SoFunction
Updated on 2024-10-30

Python's method for recording detailed call stack logs

This article example describes how Python records detailed call stack logs. Shared for your reference. Specific implementation methods are as follows:

import sys
import os
def detailtrace(info):
  retStr = ""
  curindex=0
  f = sys._getframe()
  f = f.f_back    # first frame is detailtrace, ignore it
  while hasattr(f, "f_code"):
    co = f.f_code
    retStr = "%s(%s:%s)->"%((co.co_filename),
         co.co_name,
         f.f_lineno) + retStr
    f = f.f_back
  print retStr+info
def foo():
  detailtrace("hello world")
def bar():
  foo()
def main():
  bar()
if __name__ == "__main__":
  main()

Output:

(<module>:27)->(main:24)->(bar:21)->(foo:18)->hello world

I hope that what I have described in this article will help you in your Python programming.