如何用Python记录当前行和堆栈信息?

2024-09-28 03:19:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有如下的日志功能。

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

我需要登录行号,堆栈信息。例如:

1: def hello():
2:    goodbye()
3:
4: def goodbye():
5:    printinfo()

---> Line 5: goodbye()/hello()

我怎么能用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)

给我这个信息,这正是我需要的。

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']

Tags: debuginfo信息formathellostringifstack
3条回答
import inspect
import traceback

def method():
   frame = inspect.currentframe()
   stack_trace = traceback.format_stack(frame)
   print ''.join(stack_trace)

使用堆栈跟踪[:-1]以避免在堆栈跟踪中包含方法/printinfo。

从Python 3.2开始,这可以简化为将stack_info=True标志传递给logging calls。但是,对于任何早期版本,您都需要使用上述答案之一。

当前函数名、模块和行号,只需更改格式字符串以包含它们即可。

logging.basicConfig(
    filename = fileName,
    format = "%(levelname) -10s %(asctime)s %(module)s:%(lineno)s %(funcName)s %(message)s",
    level = logging.DEBUG
)

大多数人只希望在记录异常时使用堆栈,如果调用logging.exception(),则日志模块会自动执行此操作。如果您在其他时间确实需要堆栈信息,则需要使用回溯模块来提取所需的附加信息。

相关问题 更多 >

    热门问题