12

How to ignore log entries from imported modules (not written by me)?

The setup:

import logging    
import <someOtherModule>

logging.basicConfig(level=logging.INFO)    

class myClass: 
   ...
   def some_method(self):
       logging.info('calling module')
       someOtherModule.function()
       logging.info('stuff happened')

if __name__ == "__main__":
    a = myClass().some_method()

The Log:

INFO:root:calling module
INFO:<someOtherModule>.<some dependency> <random dependency message here>
INFO:root:stuff happened

How can I get rid of that middle message?

I was not able to find an answer after looking at the logging documentation or by googling.
I found this answer but the workaround does not seem to work for me.

For the curious ones the actual log entry is:

INFO:requests.packages.urllib3.connectionpool:Starting new HTTPS connection (1): <address here>  
1
  • Top answers in linked questions are more helpful.
    – kon psych
    May 23, 2016 at 20:33

3 Answers 3

9

One work around(which I admit not a pretty one though), is to use the logging.disable method to disable the INFO logs at the time of calling the dependency methods.

class myClass: 
    ...
   def some_method(self):
       logging.info('calling module')
       logging.disable(logging.INFO)
       someOtherModule.function()
       logging.disable(logging.NOTSET)
       logging.info('stuff happened')

One advantage, I think, this gives you is that if there are any errorwarning/critical failure log messages are to be reported by the dependency module, this will allow only them. You can set the disable attribute to logging.WARNING to report only error or failure messages.

1
  • This is a much neater solution than the accepted answer. Jan 5, 2016 at 12:20
2

You can set the logging level for a given module with:

logging.getLogger("someOtherModule").setLevel(logging.WARNING)
1

We have different levels for logging, like:

      'debug': logging.DEBUG,
      'info': logging.INFO,
      'warning': logging.WARNING,
      'error': logging.ERROR,
      'critical': logging.CRITICAL

So, if you don't want to see INFO level, just raise the level, like:

logging.basicConfig(level=logging.CRITICAL)

Don't forget to change level of log for your wanted information to CRITICAL.

OR:

Try this:

...
logger = logging.getLogger()
...
logger.disabled = True
someOtherModule.function()
logger.disabled = False
...

Hope your issue solves. :)

1
  • I ended up raising the logging level. Is not as clean as I would like but it would work. thanks!
    – Randi
    Dec 30, 2014 at 19:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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