2013-05-19 69 views
38

当我使用标准模块日志记录将日志写入文件时,每个日志都会分别刷新到磁盘上吗? 例如,将下面的代码刷新日志10次?python日志记录是否刷新每个日志?

logging.basicConfig(level=logging.DEBUG, filename='debug.log') 
    for i in xrange(10): 
     logging.debug("test") 

如果是这样,它会放慢吗?

回答

44

是的,它会在每次调用时刷新输出。您可以为StreamHandler源代码中看到这一点:

def flush(self): 
    """ 
    Flushes the stream. 
    """ 
    self.acquire() 
    try: 
     if self.stream and hasattr(self.stream, "flush"): 
      self.stream.flush() 
    finally: 
     self.release() 

def emit(self, record): 
    """ 
    Emit a record. 

    If a formatter is specified, it is used to format the record. 
    The record is then written to the stream with a trailing newline. If 
    exception information is present, it is formatted using 
    traceback.print_exception and appended to the stream. If the stream 
    has an 'encoding' attribute, it is used to determine how to do the 
    output to the stream. 
    """ 
    try: 
     msg = self.format(record) 
     stream = self.stream 
     stream.write(msg) 
     stream.write(self.terminator) 
     self.flush() # <--- 
    except (KeyboardInterrupt, SystemExit): #pragma: no cover 
     raise 
    except: 
     self.handleError(record) 

我真的不会介意记录的表现,至少不会分析之前,发现这是一个瓶颈。无论如何,您总是可以创建一个Handler子类,在每次调用emit时不会执行flush(即使发生错误异常/解释器崩溃,您将面临失去大量日志的风险)。

+1

不是'flush()'方法来自[ancestor类](https://docs.python.org/2/library/logging.handlers.html#module-logging.handlers)与空身体? StreamHandler()的'flush()'方法是否覆盖它? – akhan

+1

@akhan [是。](https://hg.python.org/cpython/file/3.5/Lib/logging/__init__.py#l958) – Bakuriu