Add DEBUG logs of HTTP requests (#502)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Florimond Manca · committed by GitHub · parent 2fcf23b · Browse files · 5 files·+90 added−21 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+90 added−21 removed
- tests:+33 added−0 removed
- other:+57 added−21 removed
Provenance
- Commit
08069e9- Tree
ecae42b- Author
Florimond Manca <florimond.manca@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
2fcf23b
5 files changed+90 added−21 removed
modified:docs/environment_variables.md+45 added-18 removed
14 unmodified lines15 -----------------16 17 Valid values: `debug`, `trace` (case-insensitive)18 19-If set to `trace`, then low-level details about the execution of HTTP requests will be logged to `stderr`. This can help you debug issues and see what's exactly being sent over the wire and to which location.19+If set to `debug`, then HTTP requests will be logged to `stderr`. This is useful for general purpose reporting of network activity.20 21-The `debug` log level is currently ignored, but is planned to issue high-level logs of HTTP requests.21+If set to `trace`, then low-level details about the execution of HTTP requests will be logged to `stderr`, in addition to debug log lines. This can help you debug issues and see what's exactly being sent over the wire and to which location.22 23 Example:24 25 ```python3 unmodified lines29 with httpx.Client() as client:30 r = client.get("https://google.com")31 ```32 33+Debug output:34+35 ```console34-user@host:~$ HTTPX_LOG_LEVEL=trace python test_script.py35-20:54:17.585 - httpx.dispatch.connection_pool - acquire_connection origin=Origin(scheme='https' host='www.google.com' port=443)36-20:54:17.585 - httpx.dispatch.connection_pool - new_connection connection=HTTPConnection(origin=Origin(scheme='https' host='www.google.com' port=443))37-20:54:17.590 - httpx.dispatch.connection - start_connect host='www.google.com' port=443 timeout=TimeoutConfig(timeout=5.0)38-20:54:17.651 - httpx.dispatch.connection - connected http_version='HTTP/2'39-20:54:17.651 - httpx.dispatch.http2 - send_headers stream_id=1 headers=[(b':method', b'GET'), (b':authority', b'www.google.com'), ...]40-20:54:17.652 - httpx.dispatch.http2 - end_stream stream_id=141-20:54:17.681 - httpx.dispatch.http2 - receive_event stream_id=0 event=<RemoteSettingsChanged changed_settings:{...}>42-20:54:17.681 - httpx.dispatch.http2 - receive_event stream_id=0 event=<WindowUpdated stream_id:0, delta:983041>43-20:54:17.682 - httpx.dispatch.http2 - receive_event stream_id=0 event=<SettingsAcknowledged changed_settings:{}>44-20:54:17.739 - httpx.dispatch.http2 - receive_event stream_id=1 event=<ResponseReceived stream_id:1, headers:[(b':status', b'200'), ...]>45-20:54:17.741 - httpx.dispatch.http2 - receive_event stream_id=1 event=<DataReceived stream_id:1, flow_controlled_length:5224 data:>46-20:54:17.742 - httpx.dispatch.http2 - receive_event stream_id=1 event=<DataReceived stream_id:1, flow_controlled_length:59, data:>47-20:54:17.742 - httpx.dispatch.http2 - receive_event stream_id=1 event=<StreamEnded stream_id:1>48-20:54:17.742 - httpx.dispatch.http2 - receive_event stream_id=0 event=<PingReceived ping_data:0000000000000000>49-20:54:17.743 - httpx.dispatch.connection_pool - release_connection connection=HTTPConnection(origin=Origin(scheme='https' host='www.google.com' port=443))36+$ HTTPX_LOG_LEVEL=debug python test_script.py37+DEBUG [2019-11-06 19:11:24] httpx.client - HTTP Request: GET https://google.com "HTTP/1.1 301 Moved Permanently"38+DEBUG [2019-11-06 19:11:24] httpx.client - HTTP Request: GET https://www.google.com/ "HTTP/1.1 200 OK"39 ```40 41+Trace output:42+43+```console44+$ HTTPX_LOG_LEVEL=trace python test_script.py45+TRACE [2019-11-06 19:18:56] httpx.dispatch.connection_pool - acquire_connection origin=Origin(scheme='https' host='google.com' port=443)46+TRACE [2019-11-06 19:18:56] httpx.dispatch.connection_pool - new_connection connection=HTTPConnection(origin=Origin(scheme='https' host='google.com' port=443))47+TRACE [2019-11-06 19:18:56] httpx.config - load_ssl_context verify=True cert=None trust_env=True http_versions=HTTPVersionConfig(['HTTP/1.1', 'HTTP/2'])48+TRACE [2019-11-06 19:18:56] httpx.config - load_verify_locations cafile=/Users/florimond/Developer/python-projects/httpx/venv/lib/python3.8/site-packages/certifi/cacert.pem49+TRACE [2019-11-06 19:18:56] httpx.dispatch.connection - start_connect host='google.com' port=443 timeout=TimeoutConfig(timeout=5.0)50+TRACE [2019-11-06 19:18:56] httpx.dispatch.connection - connected http_version='HTTP/2'51+TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - send_headers stream_id=1 method='GET' target='/' headers=[(b':method', b'GET'), (b':authority', b'google.com'), (b':scheme', b'https'), (b':path', b'/'), (b'user-agent', b'python-httpx/0.7.6'), (b'accept', b'*/*'), (b'accept-encoding', b'gzip, deflate, br'), (b'connection', b'keep-alive')]52+TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - end_stream stream_id=153+TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - receive_event stream_id=0 event=<RemoteSettingsChanged changed_settings:{ChangedSetting(setting=SettingCodes.MAX_CONCURRENT_STREAMS, original_value=None, new_value=100), ChangedSetting(setting=SettingCodes.INITIAL_WINDOW_SIZE, original_value=65535, new_value=1048576), ChangedSetting(setting=SettingCodes.MAX_HEADER_LIST_SIZE, original_value=None, new_value=16384)}>54+TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - receive_event stream_id=0 event=<WindowUpdated stream_id:0, delta:983041>55+TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - receive_event stream_id=0 event=<SettingsAcknowledged changed_settings:{}>56+TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - receive_event stream_id=1 event=<ResponseReceived stream_id:1, headers:[(b':status', b'301'), (b'location', b'https://www.google.com/'), (b'content-type', b'text/html; charset=UTF-8'), (b'date', b'Wed, 06 Nov 2019 18:18:56 GMT'), (b'expires', b'Fri, 06 Dec 2019 18:18:56 GMT'), (b'cache-control', b'public, max-age=2592000'), (b'server', b'gws'), (b'content-length', b'220'), (b'x-xss-protection', b'0'), (b'x-frame-options', b'SAMEORIGIN'), (b'alt-svc', b'quic=":443"; ma=2592000; v="46,43",h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000')]>57+DEBUG [2019-11-06 19:18:56] httpx.client - HTTP Request: GET https://google.com "HTTP/2 301 Moved Permanently"58+TRACE [2019-11-06 19:18:56] httpx.dispatch.connection_pool - acquire_connection origin=Origin(scheme='https' host='www.google.com' port=443)59+TRACE [2019-11-06 19:18:56] httpx.dispatch.connection_pool - new_connection connection=HTTPConnection(origin=Origin(scheme='https' host='www.google.com' port=443))60+TRACE [2019-11-06 19:18:56] httpx.config - load_ssl_context verify=True cert=None trust_env=True http_versions=HTTPVersionConfig(['HTTP/1.1', 'HTTP/2'])61+TRACE [2019-11-06 19:18:56] httpx.config - load_verify_locations cafile=/Users/florimond/Developer/python-projects/httpx/venv/lib/python3.8/site-packages/certifi/cacert.pem62+TRACE [2019-11-06 19:18:56] httpx.dispatch.connection - start_connect host='www.google.com' port=443 timeout=TimeoutConfig(timeout=5.0)63+TRACE [2019-11-06 19:18:56] httpx.dispatch.connection - connected http_version='HTTP/2'64+TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - send_headers stream_id=1 method='GET' target='/' headers=[(b':method', b'GET'), (b':authority', b'www.google.com'), (b':scheme', b'https'), (b':path', b'/'), (b'user-agent', b'python-httpx/0.7.6'), (b'accept', b'*/*'), (b'accept-encoding', b'gzip, deflate, br'), (b'connection', b'keep-alive')]65+TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - end_stream stream_id=166+TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - receive_event stream_id=0 event=<RemoteSettingsChanged changed_settings:{ChangedSetting(setting=SettingCodes.MAX_CONCURRENT_STREAMS, original_value=None, new_value=100), ChangedSetting(setting=SettingCodes.INITIAL_WINDOW_SIZE, original_value=65535, new_value=1048576), ChangedSetting(setting=SettingCodes.MAX_HEADER_LIST_SIZE, original_value=None, new_value=16384)}>67+TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - receive_event stream_id=0 event=<WindowUpdated stream_id:0, delta:983041>68+TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - receive_event stream_id=0 event=<SettingsAcknowledged changed_settings:{}>69+TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - receive_event stream_id=1 event=<ResponseReceived stream_id:1, headers:[(b':status', b'200'), (b'date', b'Wed, 06 Nov 2019 18:18:56 GMT'), (b'expires', b'-1'), (b'cache-control', b'private, max-age=0'), (b'content-type', b'text/html; charset=ISO-8859-1'), (b'p3p', b'CP="This is not a P3P policy! See g.co/p3phelp for more info."'), (b'content-encoding', b'gzip'), (b'server', b'gws'), (b'content-length', b'5073'), (b'x-xss-protection', b'0'), (b'x-frame-options', b'SAMEORIGIN'), (b'set-cookie', b'1P_JAR=2019-11-06-18; expires=Fri, 06-Dec-2019 18:18:56 GMT; path=/; domain=.google.com; SameSite=none'), (b'set-cookie', b'NID=190=m8G9qLxCz2_4HbZI02ON2HTJF4xTvOhoJiS57Hm-OJrNS2eY20LfXMR_u-mLjujeshW5-BTezI69OGpHksT4ZK2TCDsWeU0DF7AmDTjjXFOdj30eIUTpNq7r9aWRvI8UrqiwlIsLkE8Ee3t5PiIiVdSMUcji7dkavGlMUpkMXU8; expires=Thu, 07-May-2020 18:18:56 GMT; path=/; domain=.google.com; HttpOnly'), (b'alt-svc', b'quic=":443"; ma=2592000; v="46,43",h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000')]>70+DEBUG [2019-11-06 19:18:56] httpx.client - HTTP Request: GET https://www.google.com/ "HTTP/2 200 OK"71+TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - receive_event stream_id=1 event=<DataReceived stream_id:1, flow_controlled_length:5186, data:1f8b08000000000002ffc55af97adb4692ff3f4f>72+TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - receive_event stream_id=1 event=<DataReceived stream_id:1, flow_controlled_length:221, data:>73+TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - receive_event stream_id=1 event=<StreamEnded stream_id:1>74+TRACE [2019-11-06 19:18:56] httpx.dispatch.http2 - receive_event stream_id=0 event=<PingReceived ping_data:0000000000000000>75+TRACE [2019-11-06 19:18:56] httpx.dispatch.connection_pool - release_connection connection=HTTPConnection(origin=Origin(scheme='https' host='www.google.com' port=443))76+TRACE [2019-11-06 19:18:56] httpx.dispatch.connection - close_connection77+```78+79 `SSLKEYLOGFILE`80 -----------81 82 Valid values: a filename74 unmodified linesmodified:httpx/client.py+9 added-1 removed
47 unmodified lines48 Response,49 ResponseContent,50 URLTypes,51 )52-from .utils import ElapsedTimer, get_environment_proxies, get_netrc52+from .utils import ElapsedTimer, get_environment_proxies, get_logger, get_netrc53 54+logger = get_logger(__name__)55 56+57 class BaseClient:58 def __init__(59 self,60 *,181 unmodified lines242 await response.read()243 finally:244 await response.close()245 246+ status = f"{response.status_code} {response.reason_phrase}"247+ response_line = f"{response.http_version} {status}"248+ logger.debug(249+ f'HTTP Request: {request.method} {request.url} "{response_line}"'250+ )251+252 return response253 254 def wrap(255 get_response: typing.Callable, middleware: BaseMiddleware984 unmodified linesmodified:httpx/utils.py+3 added-2 removed
192 unmodified lines193 global _LOGGER_INITIALIZED194 195 if not _LOGGER_INITIALIZED:196 _LOGGER_INITIALIZED = True197+ logging.addLevelName(TRACE_LOG_LEVEL, "TRACE")198 199 log_level = os.environ.get("HTTPX_LOG_LEVEL", "").upper()200 if log_level in ("DEBUG", "TRACE"):201 logger = logging.getLogger("httpx")202 logger.setLevel(logging.DEBUG if log_level == "DEBUG" else TRACE_LOG_LEVEL)203 handler = logging.StreamHandler(sys.stderr)204 handler.setFormatter(205 logging.Formatter(205- fmt="%(asctime)s.%(msecs)03d - %(name)s - %(message)s",206- datefmt="%H:%M:%S",206+ fmt="%(levelname)s [%(asctime)s] %(name)s - %(message)s",207+ datefmt="%Y-%m-%d %H:%M:%S",208 )209 )210 logger.addHandler(handler)211 180 unmodified linesmodified:tests/conftest.py+13 added
67 unmodified lines68 elif scope["path"].startswith("/echo_body"):69 await echo_body(scope, receive, send)70 elif scope["path"].startswith("/echo_headers"):71 await echo_headers(scope, receive, send)72+ elif scope["path"].startswith("/redirect_301"):73+ await redirect_301(scope, receive, send)74 else:75 await hello_world(scope, receive, send)76 77 70 unmodified lines148 )149 await send({"type": "http.response.body", "body": json.dumps(body).encode()})150 151 152+async def redirect_301(scope, receive, send):153+ await send(154+ {155+ "type": "http.response.start",156+ "status": 301,157+ "headers": [[b"location", b"/"]],158+ }159+ )160+ await send({"type": "http.response.body"})161+162+163 SERVER_SCOPE = "session"164 165 166 @pytest.fixture(scope=SERVER_SCOPE)137 unmodified linesmodified:tests/test_utils.py+20 added
106 unmodified lines107 async with httpx.AsyncClient() as client:108 response = await client.get(server.url)109 assert response.status_code == 200110 stderr = capsys.readouterr().err111+ assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr112 assert "httpx.dispatch.connection_pool" not in stderr113 114 115 @pytest.mark.asyncio2 unmodified lines118 async with httpx.AsyncClient() as client:119 response = await client.get(server.url)120 assert response.status_code == 200121 stderr = capsys.readouterr().err122+ assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr123 assert "httpx.dispatch.connection_pool" in stderr124 125 126+@pytest.mark.asyncio127+async def test_logs_redirect_chain(server, capsys):128+ with override_log_level("debug"):129+ async with httpx.AsyncClient() as client:130+ response = await client.get(server.url.copy_with(path="/redirect_301"))131+ assert response.status_code == 200132+133+ stderr = capsys.readouterr().err.strip()134+ redirected_request_line, ok_request_line = stderr.split("\n")135+ assert redirected_request_line.endswith(136+ "HTTP Request: GET http://127.0.0.1:8000/redirect_301 "137+ '"HTTP/1.1 301 Moved Permanently"'138+ )139+ assert ok_request_line.endswith(140+ 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"'141+ )142+143+144 def test_get_ssl_cert_file():145 # Two environments is not set.146 assert get_ca_bundle_from_env() is None147 151 unmodified lines