博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
如何禁用请求库中的日志消息?
阅读量:2290 次
发布时间:2019-05-09

本文共 2612 字,大约阅读时间需要 8 分钟。

本文翻译自:

By default, the python library writes log messages to the console, along the lines of: 默认情况下, python库按照以下方式将日志消息写入控制台:

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

I'm usually not interested in these messages, and would like to disable them. 我通常对这些消息不感兴趣,因此想禁用它们。 What would be the best way to silence those messages or decrease Requests' verbosity? 使这些消息静音或降低请求的冗长程度的最佳方法是什么?


#1楼

参考:


#2楼

I found out how to configure requests 's logging level, it's done via the standard module. 我发现了如何配置请求的日志记录级别,这是通过标准的模块完成的。 I decided to configure it to not log messages unless they are at least warnings: 我决定将其配置为不记录消息,除非它们至少是警告:

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

If you wish to apply this setting for the urllib3 library (typically used by requests) too, add the following: 如果您也希望将此设置应用于urllib3库(通常由请求使用),请添加以下内容:

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

#3楼

Let me copy/paste the documentation section which it I wrote about week or two ago, after having a problem similar to yours: 在遇到类似于您的问题之后,让我复制/粘贴一周或两周前写的文档部分:

import requestsimport 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 httplibhttplib.HTTPConnection.debuglevel = 1logging.basicConfig() # you need to initialize logging, otherwise you will not see anything from requestslogging.getLogger().setLevel(logging.DEBUG)requests_log = logging.getLogger("requests.packages.urllib3")requests_log.setLevel(logging.DEBUG)requests_log.propagate = Truerequests.get('http://httpbin.org/headers')

#4楼

import loggingurllib3_logger = logging.getLogger('urllib3')urllib3_logger.setLevel(logging.CRITICAL)

In this way all the messages of level=INFO from urllib3 won't be present in the logfile. 这样,来自urllib3的所有level = INFO消息都不会出现在日志文件中。

So you can continue to use the level=INFO for your log messages...just modify this for the library you are using. 因此,您可以继续将level = INFO用作日志消息...只需针对您正在使用的库修改它。


#5楼

For anybody using logging.config.dictConfig you can alter the requests library log level in the dictionary like this: 对于使用logging.config.dictConfig任何人,您都可以在字典中更改请求库日志级别,如下所示:

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

#6楼

简单:只需在import requests后添加requests.packages.urllib3.disable_warnings()

转载地址:http://xmcnb.baihongyu.com/

你可能感兴趣的文章