I\'m using the Python logging module, and would like to disable log messages printed by the third party modules that I import. For example, I\'m using something like the fo
In my case the only thing that helped was forcing a propagate attribute of unwanted logger to False
, i.e.
logging.getLogger("module").propagate = False
If this evaluates to false, logging messages are not passed to the handlers of ancestor loggers.
This disables all existing loggers, such as those created by imported modules, while still using the root logger (and without having to load an external file).
import logging.config
logging.config.dictConfig({
'version': 1,
'disable_existing_loggers': True,
})
Note that you need to import all modules you don't want logged first! Otherwise those won't be considered as "existing loggers". It will then disable all loggers from those modules. This might lead you to also miss out on important errors!
For more detailed examples using related options for configuration, see https://gist.github.com/st4lk/6287746, and here is a (partially working) example using YAML for config with the coloredlog
library.
Not sure if this is appropriate to post, but I was stuck for a long time & wanted to help out anyone with the same issue, as I hadn't found it anywhere else!
I was getting debug logs from matplotlib despite following the pretty straightforward documentation at the logging advanced tutorial
and the troubleshooting. I was initiating my logger in main()
of one file and importing a function to create a plot from another file (where I had imported matplotlib).
What worked for me was setting the level of matplotlib before importing it, rather than after as I had for other modules in my main file. This seemed counterintuitive to me so if anyone has insight into how you can set the config for a logger that hasn't been imported yet I'd be curious to find out how this works. Thanks!
In my main file:
import logging
import requests
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logging.getLogger('requests').setLevel(logging.DEBUG)
def main():
...
In my plot.py
file:
import logging
logging.getLogger('matplotlib').setLevel(logging.WARNING)
import matplotlib.pyplot as plt
def generatePlot():
...
You could use something like:
logging.getLogger("imported_module").setLevel(logging.WARNING)
logging.getLogger("my_own_logger_name").setLevel(logging.DEBUG)
This will set my own module's log level to DEBUG, while preventing the imported module from using the same level.
Note:
"imported_module"
can be replaced with imported_module.__name__
(without quotes), and "my_own_logger_name"
can be replaced by __name__
if that's the way you prefer to do it.