How to disable loggers from other modules?
Asked Answered
C

4

17

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?

Celia answered 18/12, 2014 at 3:40 Comment(0)
E
22

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
Exemplum answered 18/12, 2014 at 5:45 Comment(0)
P
17

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

for _ in ("boto", "elasticsearch", "urllib3"):
    logging.getLogger(_).setLevel(logging.CRITICAL)
Prorate answered 18/12, 2014 at 3:47 Comment(3)
So I still need to iterate all the modules which uses loggers by myself?Celia
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.Prorate
"explicit is better than implicit" I agree with this:)Celia
A
9

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.

Amylopsin answered 24/10, 2019 at 10:54 Comment(0)
W
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
Waggle answered 4/8, 2019 at 7:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.