Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I completely remove any logging from requests module in Python

How can I completely remove any logging from requests module in Python? I don't need to set even CRITICAL level. Smth like this

import logging
requests_log = logging.getLogger("requests")
requests_log.setLevel(logging.CRITICAL)

but without any messages, even CRITICAL.

like image 706
FrozenHeart Avatar asked Jun 21 '14 17:06

FrozenHeart


People also ask

How do I override a Python logger?

You can firstly implement your own logger class by deriving from logging. Logger, in which you override the methods you target. And then you pass the logger class to the logging system by using logging. setLoggerClass.

What is logger exception in Python?

Logging an exception in python with an error can be done in the logging. exception() method. This function logs a message with level ERROR on this logger. The arguments are interpreted as for debug(). Exception info is added to the logging message.


1 Answers

First of all, requests doesn't log anything; only the urllib3 library that requests depends on does. That library only logs messages at INFO and DEBUG levels, so setting the log level to logging.CRITICAL disables all messages already:

urllib3_log = logging.getLogger("urllib3")
urllib3_log.setLevel(logging.CRITICAL)

You could also just disable propagation:

logging.getLogger("urllib3").propagate = False

That's enough to completely disable all logging that the urllib3 library does.

The urllib3 project has installed a NullHandler() handler object on the project root logger, which ensures that the lastResort handler is not used for unhandled messages, even when propagation has been disabled.

That said, if you don't trust that future versions of requests won't use sys.maxint as a log level, and at the same time neglect to set a NullHandler(), then by all means add your own NullHandler() on the project root logger object, and then disable propagation there:

import logging

requests_log = logging.getLogger("requests")
requests_log.addHandler(logging.NullHandler())
requests_log.propagate = False

Now all logging within the requests hierarchy will be directed to the NullHandler() instance, and with propagate set to False logging stops there. You can use this to silence any logger in the hierarchy.

In my opinion, that's overkill, no requests release made so far uses logging, and the project is staffed with capable developers that are unlikely to misconfigure the logging setup if they ever did add logging.

like image 157
Martijn Pieters Avatar answered Sep 30 '22 15:09

Martijn Pieters