使用flush()自定义sys.stdout

时间:2017-07-02 18:42:09

标签: python

我正在尝试在我的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 个答案:

答案 0 :(得分:4)

将其转发给记录器的处理程序:

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