默认情况下,Requests python库将日志消息写入控制台,如下所示:
Starting new HTTP connection (1): example.com
http://example.com:80 "GET / HTTP/1.1" 200 606
我通常对这些消息不感兴趣,并希望禁用它们。什么是沉默这些消息或减少请求的冗长的最好方法?
默认情况下,Requests python库将日志消息写入控制台,如下所示:
Starting new HTTP connection (1): example.com
http://example.com:80 "GET / HTTP/1.1" 200 606
我通常对这些消息不感兴趣,并希望禁用它们。什么是沉默这些消息或减少请求的冗长的最好方法?
当前回答
我不确定之前的方法是否已经停止工作,但无论如何,这里有另一种消除警告的方法:
PYTHONWARNINGS="ignore:Unverified HTTPS request" ./do-insecure-request.py
基本上,就是在脚本执行的上下文中添加一个环境变量。
来自文档:https://urllib3.readthedocs.org/en/latest/security.html#disabling-warnings
其他回答
简单:只需在导入请求后添加requests.packages.urllib3.disable_warnings()
在我的情况下,什么帮助了我(python 3.7)
import http.client as http_client
http_client.HTTPConnection.debuglevel = 0
import logging
urllib3_logger = logging.getLogger('urllib3')
urllib3_logger.setLevel(logging.CRITICAL)
这样,来自urllib3的level=INFO的所有消息都不会出现在日志文件中。
因此,您可以继续使用level=INFO为您的日志消息…只需为您正在使用的库修改这个。
Kbrose关于查找哪个记录器正在生成日志消息的指导非常有用。对于我的Django项目,我不得不从120个不同的日志记录器中进行分类,直到我发现elasticsearch Python库给我带来了问题。根据大多数问题的指导,我通过添加这个到我的日志记录器来禁用它:
...
'elasticsearch': {
'handlers': ['console'],
'level': logging.WARNING,
},
...
在这里发布,以防其他人在运行Elasticsearch查询时看到无用的日志消息。
让我复制/粘贴文档部分,它是我在一两周前写的,在遇到类似你的问题后:
import requests
import logging
# these two lines enable debugging at httplib level (requests->urllib3->httplib)
# you will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA.
# the only thing missing will be the response.body which is not logged.
import httplib
httplib.HTTPConnection.debuglevel = 1
logging.basicConfig() # you need to initialize logging, otherwise you will not see anything from requests
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
requests.get('http://httpbin.org/headers')