2013-05-19 11 views
38

जब मैं मानक मॉड्यूल लॉगिंग का उपयोग कर फ़ाइल में लॉग लिखता हूं, तो क्या प्रत्येक लॉग डिस्क पर अलग हो जाएगा? उदाहरण के लिए, निम्नलिखित कोड 10 गुना लॉग फ्लश करेगा?क्या पाइथन लॉगिंग प्रत्येक लॉग फ्लश करता है?

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

यदि हां, तो क्या यह धीमा हो जाएगा?

उत्तर

44

हां, यह प्रत्येक कॉल पर आउटपुट को फ्लश करता है। कम से कम रूपरेखा से पहले नहीं और पता चलने पर कि यह एक टोंटी है

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) 

मैं वास्तव में प्रवेश के प्रदर्शन के बारे कोई फ़र्क नहीं पड़ेगा,: आप StreamHandler के लिए स्रोत कोड में देख सकते हैं। वैसे भी आप हमेशा Handler सबक्लास बना सकते हैं जो flush पर प्रत्येक कॉल पर emit पर प्रदर्शन नहीं करता है (भले ही आप खराब अपवाद/दुभाषिया क्रैश होने पर बहुत सारे लॉग खोने का जोखिम उठाएंगे)।

+1

खाली शरीर के साथ [पूर्वजों वर्ग] (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

संबंधित मुद्दे