2013-05-19 4 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) 

、少なくともではないプロファイリングする前に、それがボトルネックであることを発見します。とにかく、emitを呼び出すたびにflushを実行しないHandlerサブクラスを作成することはできます(悪い例外が発生するか、インタープリタがクラッシュした場合に多くのログを失う危険はありますが)。

+1

'flush()'メソッドが空のボディを持つ[ancestor class](https://docs.python.org/2/library/logging.handlers.html#module-logging.handlers)から来ていませんか? 'StreamHandlerは()'、それを上書きする 'フラッシュ()'メソッドはありますか? – akhan

+1

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

関連する問題