2013-05-19 94 views
38

當我使用標準模塊日誌記錄將日誌寫入文件時,每個日誌都會分別刷新到磁盤上嗎? 例如,將下面的代碼刷新日誌10次?python日誌記錄是否刷新每個日誌?

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

如果是這樣,它會放慢嗎?

回答

44

是的,它會在每次調用時刷新輸出。您可以爲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(即使發生錯誤異常/解釋器崩潰,您將面臨失去大量日誌的風險)。

+1

不是'flush()'方法來自[ancestor類](https://docs.python.org/2/library/logging.handlers.html#module-logging.handlers)與空身體? StreamHandler()的'flush()'方法是否覆蓋它? – akhan

+1

@akhan [是。](https://hg.python.org/cpython/file/3.5/Lib/logging/__init__.py#l958) – Bakuriu