默认情况下,Requests python库将日志消息写入控制台,如下所示:

Starting new HTTP connection (1): example.com
http://example.com:80 "GET / HTTP/1.1" 200 606

我通常对这些消息不感兴趣,并希望禁用它们。什么是沉默这些消息或减少请求的冗长的最好方法?


当前回答

让我复制/粘贴文档部分,它是我在一两周前写的,在遇到类似你的问题后:

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')

其他回答

对于任何使用logging.config.dictConfig的人来说,你可以像这样修改字典中的请求库日志级别:

'loggers': {
    '': {
        'handlers': ['file'],
        'level': level,
        'propagate': False
    },
    'requests.packages.urllib3': {
        'handlers': ['file'],
        'level': logging.WARNING
    }
}

我发现了如何配置请求的日志级别,它是通过标准日志模块完成的。我决定将其配置为不记录消息,除非它们至少是警告:

import logging

logging.getLogger("requests").setLevel(logging.WARNING)

如果你想对urllib3库(通常由请求使用)也应用这个设置,添加以下内容:

logging.getLogger("urllib3").setLevel(logging.WARNING)

如果您在这里寻找修改任何(可能嵌套很深的)模块的日志记录的方法,请使用logging. logger .manager. loggerdict来获取所有记录器对象的字典。返回的名称可以用作logging.getLogger的参数:

import requests
import logging
for key in logging.Logger.manager.loggerDict:
    print(key)
# requests.packages.urllib3.connectionpool
# requests.packages.urllib3.util
# requests.packages
# requests.packages.urllib3
# requests.packages.urllib3.util.retry
# PYREADLINE
# requests
# requests.packages.urllib3.poolmanager

logging.getLogger('requests').setLevel(logging.CRITICAL)
# Could also use the dictionary directly:
# logging.Logger.manager.loggerDict['requests'].setLevel(logging.CRITICAL)

对于注释中的user136036,请注意此方法只显示在运行上述代码段时存在的记录器。例如,如果一个模块在实例化一个类时创建了一个新的记录器,那么必须在创建类之后放入这个代码片段,以便打印它的名称。

让我复制/粘贴文档部分,它是我在一两周前写的,在遇到类似你的问题后:

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')
import logging
urllib3_logger = logging.getLogger('urllib3')
urllib3_logger.setLevel(logging.CRITICAL)

这样,来自urllib3的level=INFO的所有消息都不会出现在日志文件中。

因此,您可以继续使用level=INFO为您的日志消息…只需为您正在使用的库修改这个。