15

I use several modules in my project, however, the modules output lots of logs from the logger, which is annoying. So I turn off the logs by:

boto_log = logging.getLogger("boto")
boto_log.setLevel(logging.CRITICAL)
es_log = logging.getLogger("elasticsearch")
es_log.setLevel(logging.CRITICAL)
urllib3_log = logging.getLogger("urllib3")
urllib3_log.setLevel(logging.CRITICAL)

Though this works, the code looks verbose. Is there any better, simpler way I can do this?

4 Answers 4

18

You can disable existing loggers with either logging.config.dictConfig or logging.config.fileConfig.

import logging.config
logging.config.dictConfig({
    'version': 1,
    # Other configs ...
    'disable_existing_loggers': True
})

You can also loop over existing loggers and disable manually.

for name, logger in logging.root.manager.loggerDict.iteritems():
    logger.disabled=True
14

May be you can refactor it in order to cut some of the boilerplate:

for _ in ("boto", "elasticsearch", "urllib3"):
    logging.getLogger(_).setLevel(logging.CRITICAL)
3
  • So I still need to iterate all the modules which uses loggers by myself?
    – shihpeng
    Dec 18, 2014 at 3:51
  • 3
    Someone may came up with a better way, but at least this is not so verbose. I would say "explicit is better than implicit", so I don't think it is a bad idea to explicitly disable the logs I want to disable (instead of doing it automatically and losing some important message because of that). Looks like a good compromise between clarity and ease of use. Dec 18, 2014 at 3:54
  • "explicit is better than implicit" I agree with this:)
    – shihpeng
    Dec 18, 2014 at 3:56
8

You can get a list of all loggers (excluding the root logger) from logging.root.manager.loggerDict.

for _ in logging.root.manager.loggerDict:
    logging.getLogger(_).setLevel(logging.CRITICAL)
    # logging.getLogger(_).disabled = True  # or use this instead of CRITICAL if you'd rather completely disable it

This allows you the flexibility to put in your own filter etc if you'd rather actually keep some loggers.

1

You should know exactly name of logger which you want to disable. "urllib3.connectionpool" != "urllib3".

logging.getLogger("boto").disabled = True
logging.getLogger("elasticsearch").disabled = True
logging.getLogger("urllib3").disabled = True
logging.getLogger('urllib3.connectionpool').disabled = True

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.