本文介绍了如何编写自定义python日志记录处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何编写自定义控制台日志功能,以便仅在控制台窗口日志消息上输出一行(而不是追加),直到第一个常规日志记录为止.

How to write custom console log function to output only on the console window log messages on a single line (not append) until the first regular log record.

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')

因此控制台输出只有三行:

So that the console output is only three lines:

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

关于如何实现此目标的最佳方法的任何建议?

Any suggestions on the best way on how to implement this?

推荐答案

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()方法中有更多逻辑来处理应保留在一行上的消息和需要使用自己的一行的消息之间的更改.

Notice that only one handler is being registered, and the extra keyword argument to let the handler know it should stay on one line. There is more logic in the emit() method to handle changes between messages that should stay on one line and messages that need to have their own line.

这篇关于如何编写自定义python日志记录处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 09:55