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

发布于 2024-10-19 00:36:42 字数 1014 浏览 4 评论 0原文

我有如下记录功能。

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

玩套路吗 2024-10-26 00:36:43

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

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

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

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.

作死小能手 2024-10-26 00:36:43
import inspect
import traceback

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

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

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.

纸短情长 2024-10-26 00:36:43

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

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.

清浅ˋ旧时光 2024-10-26 00:36:43

迟到的回答,但是哦,好吧。

另一个解决方案是,您可以使用文档中指定的过滤器创建自己的格式化程序 此处。这是一个非常棒的功能,因为您现在不再需要使用辅助函数(并且必须将辅助函数放在您想要堆栈跟踪的任何地方)。相反,自定义格式将其直接实现到日志本身中。

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__)
logger.addFilter(ContextFilter(5))

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

注意:在上面的代码中,我修剪了最后 5 个堆栈帧。这只是为了方便,这样我们就不会显示 python 日志记录包本身的堆栈帧。(它也可能需要针对不同版本的日志记录包进行调整)

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__)
logger.addFilter(ContextFilter(5))

# 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)

给妤﹃绝世温柔 2024-10-26 00:36:43

使用 traceback 模块。

logging.error(traceback.format_exc())

Use the traceback module.

logging.error(traceback.format_exc())
花伊自在美 2024-10-26 00:36:43

这是一个例子,我希望它可以帮助你:

import inspect
import logging

logging.basicConfig(
    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:
        caller_list.append('{0}()'.format(frame.f_code.co_name))
        frame = frame.f_back

    caller_line = this_frame.f_back.f_lineno
    callers =  '/'.join(reversed(caller_list))

    logging.info('Line {0} : {1}'.format(caller_line, callers))

def foo():
    test()

def bar():
    foo()

bar()

结果:

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

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

import inspect
import logging

logging.basicConfig(
    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:
        caller_list.append('{0}()'.format(frame.f_code.co_name))
        frame = frame.f_back

    caller_line = this_frame.f_back.f_lineno
    callers =  '/'.join(reversed(caller_list))

    logging.info('Line {0} : {1}'.format(caller_line, callers))

def foo():
    test()

def bar():
    foo()

bar()

Result:

INFO       2011-02-23 17:03:26,426 Line 28 : bar()/foo()/test()
我早已燃尽 2024-10-26 00:36:43

查看回溯模块

>>> import traceback
>>> def test():
>>>     print "/".join( str(x[2]) for x in traceback.extract_stack() )
>>> def main():
>>>     test()
>>> main()
<module>/launch_new_instance/mainloop/mainloop/interact/push/runsource/runcode/<module>/main/test

Look at traceback module

>>> import traceback
>>> def test():
>>>     print "/".join( str(x[2]) for x in traceback.extract_stack() )
>>> def main():
>>>     test()
>>> main()
<module>/launch_new_instance/mainloop/mainloop/interact/push/runsource/runcode/<module>/main/test
辞慾 2024-10-26 00:36:43

这是基于@mouad的答案,但通过在每个级别包含文件名(但不是其完整路径)和调用堆栈的行号,并将堆栈保留在最近调用的位置(IMO),变得更有用(IMO)即不颠倒)顺序,因为这就是我想要阅读它的方式:-)

每个条目都有 file:line:func() ,它与正常的堆栈跟踪序列相同,但都在同一行上,因此更加紧凑。

import inspect

def callers(self):
    caller_list = []
    frame = inspect.currentframe()
    while frame.f_back:
        caller_list.append('{2}:{1}:{0}()'.format(frame.f_code.co_name,frame.f_lineno,frame.f_code.co_filename.split("\\")[-1]))
        frame = frame.f_back
    callers =  ' <= '.join(caller_list)
    return callers

如果您有任何中间调用来生成日志文本,您可能需要添加额外的 f_back。

        frame = inspect.currentframe().f_back

产生如下输出:

file2.py:620:func1() <= file3.py:211:func2() <= file3.py:201:func3() <= main.py:795:func4() <= file4.py:295:run() <= main.py:881:main()

我只需要在两个关键函数中使用此堆栈跟踪,因此我将调用者的输出添加到 logger.debug() 调用中的文本中,如 htis:

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

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:
        caller_list.append('{2}:{1}:{0}()'.format(frame.f_code.co_name,frame.f_lineno,frame.f_code.co_filename.split("\\")[-1]))
        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:

file2.py:620:func1() <= file3.py:211:func2() <= file3.py:201:func3() <= main.py:795:func4() <= file4.py:295:run() <= main.py:881:main()

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")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文