69

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

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

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

4

1 回答 1

71

是的,它确实会在每次调用时刷新输出。您可以在以下源代码中看到这一点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不会flush在每次调用时执行的子类emit(即使如果发生错误异常/解释器崩溃,您将有丢失大量日志的风险)。

于 2013-05-19T12:00:18.393 回答