默认情况下,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
我通常对这些消息不感兴趣,并希望禁用它们。什么是沉默这些消息或减少请求的冗长的最好方法?
当前回答
如果您有配置文件,可以对其进行配置。
在记录器部分添加urllib3:
[loggers]
keys = root, urllib3
添加logger_urllib3 section:
[logger_urllib3]
level = WARNING
handlers =
qualname = requests.packages.urllib3.connectionpool
其他回答
让我复制/粘贴文档部分,它是我在一两周前写的,在遇到类似你的问题后:
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')
如果您有配置文件,可以对其进行配置。
在记录器部分添加urllib3:
[loggers]
keys = root, urllib3
添加logger_urllib3 section:
[logger_urllib3]
level = WARNING
handlers =
qualname = requests.packages.urllib3.connectionpool
答案在这里:Python:如何从第三方库中抑制日志记录语句?
您可以为basicConfig保留默认日志级别,然后在获取模块的日志记录器时设置DEBUG级别。
logging.basicConfig(format='%(asctime)s %(module)s %(filename)s:%(lineno)s - %(message)s')
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.debug("my debug message")
将记录器名称设置为请求或请求。Urllib3不适合我。我必须指定确切的记录器名称才能更改日志级别。
首先查看您已经定义了哪些记录器,以查看您想删除哪些记录器
print(logging.Logger.manager.loggerDict)
你会看到这样的东西:
{urllib3……”。poolmanager”:<日志记录。日志对象在0x1070a6e10>, 'django。要求:<日志记录。日志对象在0x106d61290>, 'django。模板”:<日志记录。日志对象在0x10630dcd0>, 'django。服务器:<日志记录。记录器对象0x106dd6a50>, 'urllib3。连接”:<日志记录。日志记录器对象0x10710a350>,'urllib3。connectionpool”:<日志记录。日志记录器对象0x106e09690>…}
然后为确切的记录器配置级别:
'loggers': {
'': {
'handlers': ['default'],
'level': 'DEBUG',
'propagate': True
},
'urllib3.connectionpool': {
'handlers': ['default'],
'level': 'WARNING',
'propagate' : False
},
import logging
# Only show warnings
logging.getLogger("urllib3").setLevel(logging.WARNING)
# Disable all child loggers of urllib3, e.g. urllib3.connectionpool
logging.getLogger("urllib3").propagate = False