logging.handlers.BufferingHandler子类处理程序显示两次日志

时间:2017-11-29 09:44:54

标签: python logging standard-library

我通过继承logging.handlers模块中的BufferingHandler来创建自己的日志处理程序,以添加自定义刷新策略。

from logging.handlers import BufferingHandler
import logging

LOG_FORMAT = '%(asctime)s %(levelname)s: %(message)s'
logger = logging.getLogger('LogArchiver')
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter(LOG_FORMAT)

class MyLogHandler(BufferingHandler):
    def __init__(self, capacity):
        logging.handlers.BufferingHandler.__init__(self, capacity)

    def flush(self):
        for record in self.buffer:
            print(self.format(record))
            #pass

    def shouldFlush(self, record):
        return False


h = MyLogHandler(1000)
h.setLevel(logging.INFO)
h.setFormatter(formatter)
logger.addHandler(h)

if __name__ == '__main__':
    for i in range(5):
        logger.info('test %s', i)

这样做效果不错,但显示两次像LogeringHandler一样的日志行正在刷新到默认控制台,我不想要。它的印刷..

root@alok-PORTEGE-R30-A:/mnt/tmp/alok# python /tmp/testlog.py 
2017-11-29 15:01:07,480 INFO: test 0
2017-11-29 15:01:07,480 INFO: test 1
2017-11-29 15:01:07,480 INFO: test 2
2017-11-29 15:01:07,480 INFO: test 3
2017-11-29 15:01:07,480 INFO: test 4
2017-11-29 15:01:07,480 INFO: test 0
2017-11-29 15:01:07,480 INFO: test 1
2017-11-29 15:01:07,480 INFO: test 2
2017-11-29 15:01:07,480 INFO: test 3
2017-11-29 15:01:07,480 INFO: test 4

我的期望是这应该只打印

root@alok-PORTEGE-R30-A:/mnt/tmp/alok# python /tmp/testlog.py 
2017-11-29 15:01:07,480 INFO: test 0
2017-11-29 15:01:07,480 INFO: test 1
2017-11-29 15:01:07,480 INFO: test 2
2017-11-29 15:01:07,480 INFO: test 3
2017-11-29 15:01:07,480 INFO: test 4

我在控制台看到额外的同花顺?

1 个答案:

答案 0 :(得分:0)

在看到其他代码后,我发现我在刷新后错过了清空self.buffer。所以正确的代码应该是

from logging.handlers import BufferingHandler
import logging

LOG_FORMAT = '%(asctime)s %(levelname)s: %(message)s'
logger = logging.getLogger('LogArchiver')
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter(LOG_FORMAT)

class MyLogHandler(BufferingHandler):
    def __init__(self, capacity):
        logging.handlers.BufferingHandler.__init__(self, capacity)

    def flush(self):
        for record in self.buffer:
            print(self.format(record))            
        super(MyLogHandler, self).flush()

    def shouldFlush(self, record):
        return False


h = MyLogHandler(1000)
h.setLevel(logging.INFO)
h.setFormatter(formatter)
logger.addHandler(h)

if __name__ == '__main__':
    for i in range(5):
        logger.info('test %s', i)