Python缩进\上下文级别以记录前缀长度

时间:2011-03-31 11:13:25

标签: python logging

我的想法是制作上下文记录方案,如下例所示:

[   DEBUG] Parsing dialogs files
[   DEBUG] ... [DialogGroup_001]
[   DEBUG] ...... Indexing dialog xml file [c:\001_dlg.xml]
[   DEBUG] ......... dialog [LobbyA]
[   DEBUG] ............ speech nodes [3]
[   DEBUG] ............... [LobbyA_01]
[   DEBUG] ............... [LobbyA_02]
[   DEBUG] ............... [LobbyA_03]
[   DEBUG] ............ sms nodes [0]
[   DEBUG] ......... dialog [LobbyB]
[   DEBUG] ............ speech nodes [3]
[   DEBUG] ............... [LobbyB_01]
[   DEBUG] ............... [LobbyB_02]
[   DEBUG] ............... [LobbyB_03]
[   DEBUG] ............ sms nodes [0]
[   DEBUG] ... [DialogGroup_002]
[   DEBUG] ...... Indexing dialog xml file [c:\002_dlg.xml]
[   DEBUG] ......... dialog [HighGroundsA]
[   DEBUG] ............ speech nodes [3]
[   DEBUG] ............... [HighGroundsA_01]
[   DEBUG] ............... [HighGroundsA_02]
[   DEBUG] ............... [HighGroundsA_03]
[   DEBUG] ............ sms nodes [0]

此时,我正在使用Python的日志记录模块,在日志记录时使用自定义的手写前缀,例如:

(...)

log.debug('')
log.debug('Parsing dialogs files')
for dlg in defDlgList:
    log.debug('... [{0}]'.format(dlg))

(...)

它工作得很好,但有一些微妙的问题,例如:从内部函数进行日志记录时 - 可能会从各种范围调用它们,并且前缀长度可能因每次调用而异。

我正在寻找一种优雅且不可见的方法来为每个日志自动建立一个'...'前缀的长度。我宁愿避免将前缀长度作为参数传递给每个func或使用显式调用设置长度,例如:

(...)

logWrapper.debug('')
logWrapper.debug('Parsing dialogs files')
for dlg in defDlgList:
    logWrapper.nextLogLevelBegin()
    logWrapper.debug('[{0}]'.format(dlg))
    logWrapper.nextLogLevelEnd()

(...)

有没有办法从Python的解析器获取当前缩进级别或构建一个范围敏感的包装类来进行日志记录?

3 个答案:

答案 0 :(得分:12)

也许您可以使用inspect.getouterframes来查找缩进级别:

import inspect
import logging

logger=logging.getLogger(__name__)

def debug(msg):
    frame,filename,line_number,function_name,lines,index=inspect.getouterframes(
        inspect.currentframe())[1]
    line=lines[0]
    indentation_level=line.find(line.lstrip())
    logger.debug('{i} [{m}]'.format(
        i='.'*indentation_level,
        m=msg            
        ))

def foo():    
    debug('Hi Mom')
    for i in range(1):
        debug("Now we're cookin")

if __name__=='__main__':
    logging.basicConfig(level=logging.DEBUG)
    foo()

产量

DEBUG:__main__:.... [Hi Mom]
DEBUG:__main__:........ [Now we're cookin]

答案 1 :(得分:7)

通过文档搜索,我真的没有办法获得当前的缩进级别。你能做的最好的就是获得当前的函数嵌套级别,如下所示:

len(traceback.extract_stack());

示例:

import traceback;

def test():
    print len(traceback.extract_stack()); 

print len(traceback.extract_stack()); # prints 1
test(); # prints 2

答案 2 :(得分:4)

将先前的答案与How do I add custom field to Python log format string?结合使用可以获得相同的结果,而无需提供自定义的debug()方法(因为每个级别的信息(),错误()等都需要完成相同的操作

import logging
import traceback
class CustomAdapter(logging.LoggerAdapter):
    @staticmethod
    def indent():
        indentation_level = len(traceback.extract_stack())
        return indentation_level-4  # Remove logging infrastructure frames

    def process(self, msg, kwargs):
        return '{i}{m}'.format(i='\t'*self.indent(), m=msg), kwargs

logger = CustomAdapter(logging.getLogger(__name__), {})
logger.debug('A debug message')
logger.error('An error message')
logger.info('An info message')