gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:28:38 26 4
gpt4 key购买 nike

当我使用标准模块 logging 将日志写入文件时,每个日志会单独刷新到磁盘吗?比如下面的代码会刷新日志10次吗?

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

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

最佳答案

是的,它确实会在每次调用时刷新输出。您可以在 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 (即使您可能会失去很多如果发生严重异常/解释器崩溃,则记录日志)。

关于python - python日志记录是否刷新每个日志?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16633911/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com