2011-08-04 40 views
7

logging docs說調用​​方法可以「暫時限制整個應用程序的日誌記錄輸出」,但我無法找到「暫時的」。舉個例子來說,下面的腳本:Python日誌記錄:禁用的反向效果()

import logging 
logging.disable(logging.CRITICAL) 
logging.warning("test") 
# Something here 
logging.warning("test") 

到目前爲止,我一直沒能找到Something here,將重新啓用日誌記錄系統作爲一個整體,使第二warning打通。是否有與disable()相反的內容?

回答

11
logging.disable(logging.NOTSET)  
+0

好極了,和 - 回想起來 - 很明顯的:)謝謝! – Tim

+4

不像'logging.enable()'那樣明顯...... – nmichaels

+0

有什麼方法可以聯繫python文檔團隊?那裏顯然缺少一些東西。 –

0

基於由@unutbu答案,我創建了一個上下文管理器:

import logging 
log = logging.getLogger(__name__) 

class SuppressLogging: 
    """ 
    Context handler class that suppresses logging for some controlled code. 
    """ 

    def __init__(self, loglevel): 
     logging.disable(loglevel) 
     return 

    def __enter__(self): 
     return 

    def __exit__(self, exctype, excval, exctraceback): 
     logging.disable(logging.NOTSET) 
     return False 

if __name__ == "__main__": 
    logging.basicConfig(level=logging.INFO) 
    log.info("log this") 
    with SuppressLogging(logging.WARNING): 
     log.info("don't log this") 
     log.warning("don't log this warning") 
     log.error("log this error while up to WARNING suppressed") 
    log.info("log this again")