【问题标题】:How to print source code lines in python logger如何在 python 记录器中打印源代码行
【发布时间】:2011-01-14 13:36:37
【问题描述】:

是否有一些相对简单的方法可以以编程方式将源代码行包含到 python 记录器报告中。比如……

import logging

def main():
    something_is_not_right = True
    logging.basicConfig(level=logging.DEBUG,
                        format=('%(filename)s: '    
                                '%(levelname)s: '
                                '%(funcName)s(): '
                                '%(lineno)d:\t'
                                '%(message)s')
                        )

    if something_is_not_right == True:
        logging.debug('some way to get previous line of source code here?')

所以输出看起来像这样。

example.py: DEBUG: main(): 14:       if something_is_not_right == True:

【问题讨论】:

  • 不是已经这样做了吗?
  • @marcog 很抱歉我无法更清楚地解释我的问题。 TryPyPy 和 unutbu 理解我在寻找什么。希望他们的回答能解释我的追求。
  • 我也做了和marcog一样的假设,不明白问题出在哪里。也许编辑您的问题以阅读“以编程方式包含 arbitrary 源代码行,而不仅仅是记录的行”

标签: python debugging logging


【解决方案1】:
import inspect
import logging
import linecache

def main():
    something_is_not_right = True
    logging.basicConfig(level=logging.DEBUG,
                        format=('%(filename)s: '    
                                '%(levelname)s: '
                                '%(funcName)s(): '
                                '%(lineno)d:\t'
                                '%(message)s')
                        )

    if something_is_not_right:
        logging.debug(linecache.getline(
            __file__,
            inspect.getlineno(inspect.currentframe())-1))

if __name__=='__main__':
    main()

产量

test.py: DEBUG: main(): 18:     if something_is_not_right == True:

【讨论】:

  • 哇,这需要简单的____file____ 和____line____ (没有任何检查/当前帧的东西)。
【解决方案2】:

只是因为我看到 unutbu 尝试了类似的东西,所以这是我想出的代码(否则发布太晚了):

import logging, sys

# From logging.py
def currentframe():
    """Return the frame object for the caller's stack frame."""
    try:
        raise Exception
    except:
        return sys.exc_traceback

f = open(__file__.rstrip('c'))
owncode = f.readlines()
f.close()

def main():
    something_is_not_right = True
    logging.basicConfig(level=logging.DEBUG,
                        format=('%(filename)s: '
                                '%(levelname)s: '
                                '%(funcName)s(): '
                                '%(lineno)d:\t'
                                '%(message)s')
                        )

    if something_is_not_right == True:
        prev = owncode[currentframe().tb_frame.f_back.f_lineno - 2]
        logging.debug('previous line of source code here:\n%s' % prev)

if __name__ == '__main__':
    main()

【讨论】:

    猜你喜欢
    • 2010-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-04
    • 2015-12-26
    • 2020-02-23
    相关资源
    最近更新 更多