logging docs表示调用logging.disable(lvl)
方法可以“暂时限制整个应用程序的日志记录输出”,但我找不到“暂时”。举例来说,以下脚本:
import logging
logging.disable(logging.CRITICAL)
logging.warning("test")
# Something here
logging.warning("test")
到目前为止,我还没有找到将Something here
作为一个整体重新启用日志系统并允许第二个warning
通过的disable()
。是否与{{1}}相反?
答案 0 :(得分:12)
logging.disable(logging.NOTSET)
答案 1 :(得分: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")