使用flush()自定义sys.stdout

4

我正在尝试在我的MeowLogTool Python日志记录器中创建自定义sys.stdout。

以下是该类:

class StreamToLogger(object):
   """
   Source: https://www.electricmonk.nl/log/2011/08/14/redirect-stdout-and-stderr-to-a-logger-in-python/
   Fake file-like stream object that redirects writes to a logger instance.
   """
   def __init__(self, logger, log_level=logging.INFO):
      self.logger = logger
      self.log_level = log_level
      self.linebuf = ''

   def write(self, buf):
      for line in buf.rstrip().splitlines():
         self.logger.log(self.log_level, line.rstrip())

然而,有时候我会遇到关于flush()的错误。
 'StreamToLogger' object has no attribute 'flush'

我不知道如何为我的特定情况编写flush()函数。我找不到带有flush()的自定义sys.stdout的示例。

我想问如何编写flush()函数。

1个回答

6

将其转发到日志记录器的处理程序:

def flush(self):
    for handler in self.logger.handlers:
        handler.flush()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接