2013-05-19 11 views
38

günlük numaralı günlük modülünü kullanarak bir günlük dosyasına dosya yazdığımda, her bir günlük ayrı olarak diske temizlenir mi? Örneğin, aşağıdaki kod oturumunu 10 kez temizler mi?Python günlüğü her günlüğünü temizler mi?

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

Eğer öyleyse, yavaşlayacak mı?

cevap

44

Evet, çıkışı her aramada temizler. Sen StreamHandler kaynak koduna bunu görebilirsiniz: Gerçekten günlük performansı hakkında sakıncası olmaz

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) 

, en azından profilleme önce ve bir darboğaz olduğunu keşfetmek. Her neyse, her zaman emit'a yapılan her aramada flush gerçekleştirmeyen bir Handler alt sınıfı yaratabilirsiniz (kötü bir istisna oluşursa/yorumlayıcı çökerse çok fazla günlük kaybetme riskiniz olsa bile).

+1

Boş bedenle [acestor sınıfından] (https://docs.python.org/2/library/logging.handlers.html#module-logging.handlers) gelen flush() yöntemi değil midir? StreamHandler() 'i flush()' yöntemi geçersiz kılıyor mu? – akhan

+1

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

İlgili konular