是的,它會在每次調用時刷新輸出。您可以爲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
(即使發生錯誤異常/解釋器崩潰,您將面臨失去大量日誌的風險)。
不是'flush()'方法來自[ancestor類](https://docs.python.org/2/library/logging.handlers.html#module-logging.handlers)與空身體? StreamHandler()的'flush()'方法是否覆蓋它? – akhan
@akhan [是。](https://hg.python.org/cpython/file/3.5/Lib/logging/__init__.py#l958) – Bakuriu