当我使用标准模块日志记录将日志写入文件时,是否会将每个日志分别刷新到磁盘? 例如,以下代码会将日志刷新10次吗?
logging.basicConfig(level=logging.DEBUG, filename='debug.log')
for i in xrange(10):
logging.debug("test")
如果是这样,它会慢下来吗?
答案 0 :(得分:53)
是的,它会在每次通话时刷新输出。您可以在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
(即使你发现一个错误的异常会丢失很多日志/翻译崩溃)。