簡體   English   中英

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

[英]How to print source code lines in python logger

是否有一些相對簡單的方法以編程方式將源代碼行包含到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:
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:

只是因為我看到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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM