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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16633911/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:13:20  来源:igfitidea点击:

Does python logging flush every log?

pythonperformanceloggingflush

提问by Vincent Xue

When I write a log to file using the standard module logging, will each log be flushed to disk separately? For example, will the following code flush log by 10 times?

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

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

if so, will it slow down ?

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

采纳答案by Bakuriu

Yes, it does flush the output at every call. You can see this in the source code for the StreamHandler:

是的,它会在每次调用时刷新输出。您可以在以下源代码中看到这一点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)

I wouldn't really mind about the performance of logging, at least not before profiling and discovering that it is a bottleneck. Anyway you can always create a Handlersubclass that doesn't perform flushat every call to emit(even though you will risk to lose a lot of logs if a bad exception occurs/the interpreter crashes).

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