Python Logging - Disable logging from imported modules

前端 未结 10 832
清酒与你
清酒与你 2020-12-12 12:52

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

10条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-12 13:38

    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():
      ...
    

提交回复
热议问题