2011-01-14 66 views
8

是否有一些相對簡單的方式來編程將源代碼行包含到Python日誌記錄器報告中。例如...如何打印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: 
+0

隱而不宣」那已經做到了嗎? – marcog 2011-01-14 13:45:42

+0

@marcog對不起,我無法更清楚地解釋我的問題。 TryPyPy和unutbu明白我在找什麼。希望他們的答案能夠解釋我之後的情況。 – ojs 2011-01-15 09:41:21

回答

12
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: 
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() 
相關問題