{...'urllib3.poolmanager': <logging.Logger object at 0x1070a6e10>, 'django.request': <logging.Logger object at 0x106d61290>, 'django.template': <logging.Logger object at 0x10630dcd0>, 'django.server': <logging.Logger object at 0x106dd6a50>, 'urllib3.connection': <logging.Logger object at 0x10710a350>,'urllib3.connectionpool': <logging.Logger object at 0x106e09690> ...}
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')
10 回答
这样,来自urllib3的level = INFO的所有消息都不会出现在日志文件中 .
因此,您可以继续使用level = INFO作为日志消息...只需为您正在使用的库修改此值 .
简单:只需在
import requests
之后添加requests.packages.urllib3.disable_warnings()
如果您有配置文件,则可以对其进行配置 .
在loggers部分添加urllib3:
添加logger_urllib3部分:
我发现了如何通过标准logging模块配置请求's logging level, it's . 我决定将其配置为不记录消息,除非它们至少是警告:
如果您希望将此设置应用于urllib3库(通常由请求使用),请添加以下内容:
如果您来到这里寻找修改任何(可能是深度嵌套的)模块的日志记录的方法,请使用
logging.Logger.manager.loggerDict
获取所有 Logger 对象的字典 . 返回的名称可以用作logging.getLogger
的参数:注释中的每个用户136036,请注意此方法仅显示运行上述代码段时存在的 Logger . 例如,如果模块在实例化类时创建新的 Logger ,则必须在创建类之后放置此片段以打印其名称 .
将 Logger 名称设置为
requests
或requests.urllib3
对我来说不起作用 . 我必须指定确切的 Logger 名称来更改日志记录级别 .首先查看您已定义的 Logger ,以查看要删除的 Logger
你会看到这样的事情:
{...'urllib3.poolmanager': <logging.Logger object at 0x1070a6e10>, 'django.request': <logging.Logger object at 0x106d61290>, 'django.template': <logging.Logger object at 0x10630dcd0>, 'django.server': <logging.Logger object at 0x106dd6a50>, 'urllib3.connection': <logging.Logger object at 0x10710a350>,'urllib3.connectionpool': <logging.Logger object at 0x106e09690> ...}
然后配置精确 Logger 的级别:
在遇到与您类似的问题之后,让我复制/粘贴我在一两年前写过的文档部分:
我不确定以前的方法是否已经停止工作,但无论如何,这是另一种删除警告的方法:
基本上,在脚本执行的上下文中添加环境变量 .
从文档:https://urllib3.readthedocs.org/en/latest/security.html#disabling-warnings
对于使用
logging.config.dictConfig
的任何人,您可以在字典中更改请求库日志级别,如下所示:Kbrose关于找到哪个 Logger 生成日志消息的指导非常有用 . 对于我的Django项目,我不得不对120种不同的 Logger 进行排序,直到我发现它是
elasticsearch
Python库,这对我来说是个问题 . 根据大多数问题的指导,我通过将其添加到 Logger 来禁用它:发布此处以防其他人在运行Elasticsearch查询时看到无用的日志消息 .