如何在python logger中打印源代码行

时间:2011-01-14 13:36:37

标签: python debugging logging

是否有一些相对简单的方法以编程方式将源代码行包含到python logger报告中。例如......

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:

2 个答案:

答案 0 :(得分:15)

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:

答案 1 :(得分:4)

仅仅因为我看到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()