我正在使用python Requests。我需要调试一些OAuth
活动,为此我希望它能记录所有正在执行的请求。我可以使用ngrep
获取此信息,但不幸的是,无法grep https连接(OAuth
所需的)
如何激活Requests
正在访问的所有网址(+参数)的记录?
答案 0 :(得分:93)
您需要在httplib
级别(requests
→urllib3
→httplib
)启用调试。
这里有一些功能可以切换(..._on()
和..._off()
)或暂时启用它:
import logging
import contextlib
try:
from http.client import HTTPConnection # py3
except ImportError:
from httplib import HTTPConnection # py2
def debug_requests_on():
'''Switches on logging of the requests module.'''
HTTPConnection.debuglevel = 1
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
def debug_requests_off():
'''Switches off logging of the requests module, might be some side-effects'''
HTTPConnection.debuglevel = 0
root_logger = logging.getLogger()
root_logger.setLevel(logging.WARNING)
root_logger.handlers = []
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.WARNING)
requests_log.propagate = False
@contextlib.contextmanager
def debug_requests():
'''Use with 'with'!'''
debug_requests_on()
yield
debug_requests_off()
演示使用:
>>> requests.get('http://httpbin.org/')
<Response [200]>
>>> debug_requests_on()
>>> requests.get('http://httpbin.org/')
INFO:requests.packages.urllib3.connectionpool:Starting new HTTP connection (1): httpbin.org
DEBUG:requests.packages.urllib3.connectionpool:"GET / HTTP/1.1" 200 12150
send: 'GET / HTTP/1.1\r\nHost: httpbin.org\r\nConnection: keep-alive\r\nAccept-
Encoding: gzip, deflate\r\nAccept: */*\r\nUser-Agent: python-requests/2.11.1\r\n\r\n'
reply: 'HTTP/1.1 200 OK\r\n'
header: Server: nginx
...
<Response [200]>
>>> debug_requests_off()
>>> requests.get('http://httpbin.org/')
<Response [200]>
>>> with debug_requests():
... requests.get('http://httpbin.org/')
INFO:requests.packages.urllib3.connectionpool:Starting new HTTP connection (1): httpbin.org
...
<Response [200]>
您将看到REQUEST,包括HEADERS和DATA,以及带有HEADERS但没有DATA的RESPONSE。唯一缺少的是没有记录的response.body。
答案 1 :(得分:60)
基础urllib3
库会使用logging
module而非POST
主体记录所有新连接和网址。对于GET
请求,这应该足够了:
import logging
logging.basicConfig(level=logging.DEBUG)
为您提供最详细的日志记录选项;有关如何配置日志记录级别和目标的更多详细信息,请参阅logging HOWTO。
简短演示:
>>> import requests
>>> import logging
>>> logging.basicConfig(level=logging.DEBUG)
>>> r = requests.get('http://httpbin.org/get?foo=bar&baz=python')
INFO:requests.packages.urllib3.connectionpool:Starting new HTTP connection (1): httpbin.org
DEBUG:requests.packages.urllib3.connectionpool:"GET /get?foo=bar&baz=python HTTP/1.1" 200 353
记录以下消息:
INFO
:新连接(HTTP或HTTPS)INFO
:丢弃的连接INFO
:重定向WARN
:连接池已满(如果发生这种情况,通常会增加连接池大小)WARN
:正在重试连接DEBUG
:连接详细信息:方法,路径,HTTP版本,状态代码和响应长度答案 2 :(得分:33)
对于那些使用python 3 +
的人import requests
import logging
import http.client
http.client.HTTPConnection.debuglevel = 1
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
答案 3 :(得分:7)
当尝试使Python日志记录系统(import logging
)发出低级调试日志消息时,我很惊讶地发现给定的内容:
requests --> urllib3 --> http.client.HTTPConnection
只有urllib3
实际上使用Python logging
系统:
requests
否 http.client.HTTPConnection
否 urllib3
是 当然,您可以通过设置以下内容来从HTTPConnection
中提取调试消息:
HTTPConnection.debuglevel = 1
,但是这些输出仅通过print
语句发出。为了证明这一点,只需grep Python 3.7 client.py
源代码并亲自查看打印语句(感谢@Yohann):
curl https://raw.githubusercontent.com/python/cpython/3.7/Lib/http/client.py |grep -A1 debuglevel`
大概以某种方式重定向stdout可能会起作用,从而将stdout塞入日志系统并有可能捕获到例如日志文件。
urllib3
”记录器而不是“ requests.packages.urllib3
” 要通过Python 3 urllib3
系统捕获logging
调试信息,这与互联网上的许多建议相反,并且正如@MikeSmith指出的那样,您不会有很多运气拦截:
log = logging.getLogger('requests.packages.urllib3')
相反,您需要:
log = logging.getLogger('urllib3')
urllib3
到日志文件以下是一些使用Python urllib3
系统将logging
的工作记录到日志文件中的代码:
import requests
import logging
from http.client import HTTPConnection # py3
# log = logging.getLogger('requests.packages.urllib3') # useless
log = logging.getLogger('urllib3') # works
log.setLevel(logging.DEBUG) # needed
fh = logging.FileHandler("requests.log")
log.addHandler(fh)
requests.get('http://httpbin.org/')
结果:
Starting new HTTP connection (1): httpbin.org:80
http://httpbin.org:80 "GET / HTTP/1.1" 200 3168
HTTPConnection.debuglevel
print()语句如果您设置了HTTPConnection.debuglevel = 1
from http.client import HTTPConnection # py3
HTTPConnection.debuglevel = 1
requests.get('http://httpbin.org/')
您将获得 print 语句输出的其他多汁低级信息:
send: b'GET / HTTP/1.1\r\nHost: httpbin.org\r\nUser-Agent: python-
requests/2.22.0\r\nAccept-Encoding: gzip, deflate\r\nAccept: */*\r\nConnection: keep-alive\r\n\r\n'
reply: 'HTTP/1.1 200 OK\r\n'
header: Access-Control-Allow-Credentials header: Access-Control-Allow-Origin
header: Content-Encoding header: Content-Type header: Date header: ...
请记住,此输出使用print
而不是Python logging
系统,因此无法使用传统的logging
流或文件处理程序捕获(尽管可能会通过重定向stdout将输出捕获到文件中)。
要最大限度地利用所有可能的日志记录,您必须使用以下命令满足控制台/ stdout输出的要求:
import requests
import logging
from http.client import HTTPConnection # py3
log = logging.getLogger('urllib3')
log.setLevel(logging.DEBUG)
# logging from urllib3 to console
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
log.addHandler(ch)
# print statements from `http.client.HTTPConnection` to console/stdout
HTTPConnection.debuglevel = 1
requests.get('http://httpbin.org/')
提供完整的输出范围:
Starting new HTTP connection (1): httpbin.org:80
send: b'GET / HTTP/1.1\r\nHost: httpbin.org\r\nUser-Agent: python-requests/2.22.0\r\nAccept-Encoding: gzip, deflate\r\nAccept: */*\r\nConnection: keep-alive\r\n\r\n'
reply: 'HTTP/1.1 200 OK\r\n'
http://httpbin.org:80 "GET / HTTP/1.1" 200 3168
header: Access-Control-Allow-Credentials header: Access-Control-Allow-Origin
header: Content-Encoding header: ...
答案 4 :(得分:4)
具有用于网络协议调试的脚本或什至是应用程序的子系统,希望看到确切的请求-响应对,包括有效的URL,标头,有效负载和状态。通常,在各地检测单个请求是不切实际的。同时,出于性能方面的考虑,建议使用单个(或很少几个专用)requests.Session
,因此以下假设遵循the suggestion。
requests
支持所谓的event hooks(从2.23开始,实际上只有response
挂钩)。从本质上讲,它是一个事件侦听器,并且在从requests.request
返回控制之前发出事件。此时,请求和响应都已完全定义,因此可以记录下来。
import logging
import requests
logger = logging.getLogger('httplogger')
def logRoundtrip(response, *args, **kwargs):
extra = {'req': response.request, 'res': response}
logger.debug('HTTP roundtrip', extra=extra)
session = requests.Session()
session.hooks['response'].append(logRoundtrip)
基本上,这就是记录会话的所有HTTP往返的方式。
要使上面的日志记录有用,可以使用专门的logging formatter来了解日志记录中的req
和res
的其他内容。看起来可能像这样:
import textwrap
class HttpFormatter(logging.Formatter):
def _formatHeaders(self, d):
return '\n'.join(f'{k}: {v}' for k, v in d.items())
def formatMessage(self, record):
result = super().formatMessage(record)
if record.name == 'httplogger':
result += textwrap.dedent('''
---------------- request ----------------
{req.method} {req.url}
{reqhdrs}
{req.body}
---------------- response ----------------
{res.status_code} {res.reason} {res.url}
{reshdrs}
{res.text}
''').format(
req=record.req,
res=record.res,
reqhdrs=self._formatHeaders(record.req.headers),
reshdrs=self._formatHeaders(record.res.headers),
)
return result
formatter = HttpFormatter('{asctime} {levelname} {name} {message}', style='{')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logging.basicConfig(level=logging.DEBUG, handlers=[handler])
现在,如果您使用session
进行某些请求,例如:
session.get('https://httpbin.org/user-agent')
session.get('https://httpbin.org/status/200')
stderr
的输出如下所示。
2020-05-14 22:10:13,224 DEBUG urllib3.connectionpool Starting new HTTPS connection (1): httpbin.org:443
2020-05-14 22:10:13,695 DEBUG urllib3.connectionpool https://httpbin.org:443 "GET /user-agent HTTP/1.1" 200 45
2020-05-14 22:10:13,698 DEBUG httplogger HTTP roundtrip
---------------- request ----------------
GET https://httpbin.org/user-agent
User-Agent: python-requests/2.23.0
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive
None
---------------- response ----------------
200 OK https://httpbin.org/user-agent
Date: Thu, 14 May 2020 20:10:13 GMT
Content-Type: application/json
Content-Length: 45
Connection: keep-alive
Server: gunicorn/19.9.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
{
"user-agent": "python-requests/2.23.0"
}
2020-05-14 22:10:13,814 DEBUG urllib3.connectionpool https://httpbin.org:443 "GET /status/200 HTTP/1.1" 200 0
2020-05-14 22:10:13,818 DEBUG httplogger HTTP roundtrip
---------------- request ----------------
GET https://httpbin.org/status/200
User-Agent: python-requests/2.23.0
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive
None
---------------- response ----------------
200 OK https://httpbin.org/status/200
Date: Thu, 14 May 2020 20:10:13 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 0
Connection: keep-alive
Server: gunicorn/19.9.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
当您有很多查询时,使用简单的UI和筛选记录的方法就很方便。我将为此使用Chronologer(我是作者)。
首先,钩子已被重写以产生记录,logging
可以在通过电线发送时进行序列化。看起来可能像这样:
def logRoundtrip(response, *args, **kwargs):
extra = {
'req': {
'method': response.request.method,
'url': response.request.url,
'headers': response.request.headers,
'body': response.request.body,
},
'res': {
'code': response.status_code,
'reason': response.reason,
'url': response.url,
'headers': response.headers,
'body': response.text
},
}
logger.debug('HTTP roundtrip', extra=extra)
session = requests.Session()
session.hooks['response'].append(logRoundtrip)
第二,必须修改日志记录配置以使用logging.handlers.HTTPHandler
(Chronologer理解)。
import logging.handlers
chrono = logging.handlers.HTTPHandler(
'localhost:8080', '/api/v1/record', 'POST', credentials=('logger', ''))
handlers = [logging.StreamHandler(), chrono]
logging.basicConfig(level=logging.DEBUG, handlers=handlers)
最后,运行Chronologer实例。例如使用Docker:
docker run --rm -it -p 8080:8080 -v /tmp/db \
-e CHRONOLOGER_STORAGE_DSN=sqlite:////tmp/db/chrono.sqlite \
-e CHRONOLOGER_SECRET=example \
-e CHRONOLOGER_ROLES="basic-reader query-reader writer" \
saaj/chronologer \
python -m chronologer -e production serve -u www-data -g www-data -m
然后再次运行请求:
session.get('https://httpbin.org/user-agent')
session.get('https://httpbin.org/status/200')
流处理程序将产生:
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): httpbin.org:443
DEBUG:urllib3.connectionpool:https://httpbin.org:443 "GET /user-agent HTTP/1.1" 200 45
DEBUG:httplogger:HTTP roundtrip
DEBUG:urllib3.connectionpool:https://httpbin.org:443 "GET /status/200 HTTP/1.1" 200 0
DEBUG:httplogger:HTTP roundtrip
现在,如果您打开http://localhost:8080/(使用“ logger”作为用户名,并使用空密码作为基本auth弹出窗口),然后单击“ Open”按钮,您应该会看到类似的内容:
答案 5 :(得分:3)
我正在使用python 3.4,要求2.19.1:
“ urllib3”是现在要获取的记录器(不再是“ requests.packages.urllib3”)。在不设置http.client.HTTPConnection.debuglevel
的情况下,仍然会进行基本日志记录答案 6 :(得分:0)
我正在使用logger_config.yaml
文件配置日志记录,并使这些日志显示出来,我所要做的就是在其末尾添加一个disable_existing_loggers: False
。
我的日志记录设置相当广泛且令人困惑,因此我什至不知道在这里对其进行解释的好方法,但是如果有人也在使用YAML文件配置其日志记录,则可能会有所帮助。
https://docs.python.org/3/howto/logging.html#configuring-logging
答案 7 :(得分:0)
只需改善this答案
这对我来说是这样的:
import logging
import sys
import requests
import textwrap
root = logging.getLogger('httplogger')
def logRoundtrip(response, *args, **kwargs):
extra = {'req': response.request, 'res': response}
root.debug('HTTP roundtrip', extra=extra)
class HttpFormatter(logging.Formatter):
def _formatHeaders(self, d):
return '\n'.join(f'{k}: {v}' for k, v in d.items())
def formatMessage(self, record):
result = super().formatMessage(record)
if record.name == 'httplogger':
result += textwrap.dedent('''
---------------- request ----------------
{req.method} {req.url}
{reqhdrs}
{req.body}
---------------- response ----------------
{res.status_code} {res.reason} {res.url}
{reshdrs}
{res.text}
''').format(
req=record.req,
res=record.res,
reqhdrs=self._formatHeaders(record.req.headers),
reshdrs=self._formatHeaders(record.res.headers),
)
return result
formatter = HttpFormatter('{asctime} {levelname} {name} {message}', style='{')
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(formatter)
root.addHandler(handler)
root.setLevel(logging.DEBUG)
session = requests.Session()
session.hooks['response'].append(logRoundtrip)
session.get('http://httpbin.org')