10

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.

3
  • have you tried calling logging.disable() again with a higher logging level? Commented May 17, 2012 at 14:36
  • @MikeCorcoran this would disable even more logs. I could try to disable(logging.DEBUG) but this would mute debug messages. Commented May 17, 2012 at 14:53
  • try passing zero to logging.disable() Commented May 17, 2012 at 15:04

1 Answer 1

15

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
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks. It seems this info is missing from the documentation.
I edited the answer to use the constant logging.NOTSET instead of magical "0".
In fact my question is a duplicate of stackoverflow.com/questions/6948190/… which has the correct answer. Didn't find any "mark as dupe" button, maybe I don't have enough karma or badges...
For info, I submitted a doc bug to bugs.python.org and it was fixed in less than one hour, so next time someone has the issue we probably can redirect to official documentation.
See meta.stackexchange.com/questions/118124/… for flagging as duplicate

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.