Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable loggers from other modules?

Tags:

python

logging

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?

like image 322
shihpeng Avatar asked Dec 18 '14 03:12

shihpeng


People also ask

Does logging module use log4j?

The inbuilt logging module in python requires some handful of lines of code to configure log4j-like features viz - file appender, file rotation based on both time & size. For one-liner implementation of the features in your code, you can use the package autopylogger . Here are the basics.


2 Answers

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
like image 200
Leonardo.Z Avatar answered Sep 21 '22 18:09

Leonardo.Z


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

for _ in ("boto", "elasticsearch", "urllib3"):
    logging.getLogger(_).setLevel(logging.CRITICAL)
like image 26
Paulo Scardine Avatar answered Sep 21 '22 18:09

Paulo Scardine