Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to undo a logging.disable() command in logging module in Python? [duplicate]

Tags:

python

logging

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.

like image 609
gb. Avatar asked Dec 28 '22 00:12

gb.


1 Answers

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
like image 189
Mike Corcoran Avatar answered Dec 30 '22 10:12

Mike Corcoran