2013-05-19 9 views
38

Quando si scrive un registro in un file utilizzando il modulo standard registrazione, ciascun registro verrà svuotato su disco separatamente? Ad esempio, il seguente codice svuoterà il registro di 10 volte?La registrazione Python esegue il flush di ogni registro?

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

in tal caso, rallenterà?

risposta

44

Sì, elimina l'output ad ogni chiamata. Si può vedere questo nel codice sorgente per il 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) 

non mi sarebbe davvero importa circa le prestazioni di registrazione, almeno non prima di profilazione e scoprendo che è un collo di bottiglia. In ogni caso è sempre possibile creare una sottoclasse Handler che non esegue flush ad ogni chiamata a emit (anche se si rischia di perdere molti registri se si verifica un'eccezione errata/l'interprete si arresta in modo anomalo).

+1

Il metodo 'flush()' non viene fornito dalla classe [antenato] (https://docs.python.org/2/library/logging.handlers.html#module-logging.handlers) con il corpo vuoto? Il metodo 'flush()' per 'StreamHandler()' lo sovrascrive? – akhan

+1

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

Problemi correlati