如何从Python中的请求模块中完全删除任何日志记录 [英] How can I completely remove any logging from requests module in Python
问题描述
如何在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.
推荐答案
首先,requests
不记录任何内容;仅requests
依赖的urllib3
库起作用.该库仅记录INFO
和DEBUG
级别的消息,因此将日志级别设置为logging.CRITICAL
会禁用所有已经存在的消息
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)
您还可以仅禁用传播:
logging.getLogger("urllib3").propagate = False
这足以完全禁用urllib3
库所做的所有日志记录.
That's enough to completely disable all logging that the urllib3
library does.
urllib3
项目已安装 NullHandler()
项目根记录器上的处理程序对象,可确保 lastResort
处理程序不会用于未处理的消息,即使传播已被禁用.
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.
也就是说,如果您不相信requests
的将来版本不会将sys.maxint
用作日志级别,而同时又忽略了设置NullHandler()
,那么请务必添加您的在项目根记录器对象上拥有NullHandler()
,然后在此处禁用传播:
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
现在,requests
层次结构中的所有日志记录都将定向到NullHandler()
实例,并且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.
我认为这太过分了,到目前为止,没有发布任何requests
版本使用日志记录,并且该项目配备了有能力的开发人员,如果他们确实添加了日志记录,则他们不太可能会错误地配置日志记录设置.
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.
这篇关于如何从Python中的请求模块中完全删除任何日志记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!