如何编写自定义python日志处理程序?

时间:2010-06-25 12:43:51

标签: python logging console

如何将自定义控制台日志功能编写为仅在控制台窗口上输出日志消息在一行(不附加)上直到第一个常规日志记录。

progress = ProgressConsoleHandler()
console  = logging.StreamHandler()  

logger = logging.getLogger('test')
logger.setLevel(logging.DEBUG) 
logger.addHandler(console)  
logger.addHandler(progress)

logger.info('test1')
for i in range(3):
    logger.progress('remaining %d seconds' % i)
    time.sleep(1)   
logger.info('test2')

这样控制台输出只有三行:

INFO: test1
remaining 0 seconds... 
INFO: test2

有关如何实施此方法的最佳方法的任何建议?

1 个答案:

答案 0 :(得分:53)

import logging
class ProgressConsoleHandler(logging.StreamHandler):
    """
    A handler class which allows the cursor to stay on
    one line for selected messages
    """
    on_same_line = False
    def emit(self, record):
        try:
            msg = self.format(record)
            stream = self.stream
            same_line = hasattr(record, 'same_line')
            if self.on_same_line and not same_line:
                stream.write(self.terminator)
            stream.write(msg)
            if same_line:
                stream.write('... ')
                self.on_same_line = True
            else:
                stream.write(self.terminator)
                self.on_same_line = False
            self.flush()
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record)
if __name__ == '__main__':
    import time
    progress = ProgressConsoleHandler()
    console  = logging.StreamHandler()  

    logger = logging.getLogger('test')
    logger.setLevel(logging.DEBUG) 
    logger.addHandler(progress)

    logger.info('test1')
    for i in range(3):
        logger.info('remaining %d seconds', i, extra={'same_line':True})
        time.sleep(1)   
    logger.info('test2')

请注意,只有一个处理程序正在注册,而extra关键字参数让处理程序知道它应该保持在一行。 emit()方法中有更多逻辑来处理应保留在一行上的消息与需要拥有自己的行的消息之间的更改。