In the powerful logging built-in module in Python, it is possible to disable all logs below a level by calling, for example, logging.disable(logging.INFO)
.
I did not find how to reset or undo this setting in the doc.
My purpose is to disable and re-enable info and debugging level logs when doing unittests, by calling logging.disable in setUp()
, then calling (what?) in tearDown()
.
NB: I know how to do it if I have a give logger
instance: keep logger.level
, set the level higher, then set it back in tearDown()
. I would prefer a way to mute all loggers without choosing them explicitly.
It looks like the answer is to call logging.disable(logging.NOTSET)
import logging
logger = logging.getLogger('testlog')
handler = logging.FileHandler('\\path\\to\\testlog.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
logger.error("some error occurred")
logger.info('some info msg')
logging.disable(logging.ERROR)
logger.info('another info msg')
logging.disable(logging.NOTSET)
logger.info('last info msg')
results in a log file with this output:
2012-05-17 11:09:24,441 ERROR some error occurred
2012-05-17 11:09:24,443 INFO some info msg
2012-05-17 11:09:24,443 INFO last info msg
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With