python日志记录是否会刷新每个日志?

Vin*_*Xue 52 python performance logging flush

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

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

如果是这样,它会慢下来吗?

Bak*_*riu 55

是的,它会在每次通话时刷新输出.您可以在源代码中看到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)
Run Code Online (Sandbox Code Playgroud)

我不会真正关心日志记录的性能,至少在分析和发现它是瓶颈之前不会这样.无论如何,你总是可以创建一个在每次调用时Handler都不执行的子类(即使发生错误异常/解释器崩溃,你也有可能丢失大量日志).flushemit