Python logging: reverse effects of disable()

后端 未结 2 1037
南方客
南方客 2021-01-05 00:01

The logging docs say that calling the logging.disable(lvl) method can \"temporarily throttle logging output down across the whole application,\" but I\'m having

相关标签:
2条回答
  • 2021-01-05 00:47

    Based on the answer by @unutbu, I created a context manager:

    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")
    
    0 讨论(0)
  • 2021-01-05 00:57
    logging.disable(logging.NOTSET)    
    
    0 讨论(0)
提交回复
热议问题