How can I completely remove any logging from reque

2019-05-24 21:15发布

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.

1条回答
走好不送
2楼-- · 2019-05-24 22:13

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.

查看更多
登录 后发表回答