Add easier debug logging for users (#277)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Seth Michael Larson · committed by GitHub · parent 33032df · Browse files · 9 files·+172 added−1 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-Authored-By: Florimond Manca <florimond.manca@gmail.com>
Diff stats
9 files+172 added−1 removed
- tests:+24 added−0 removed
- other:+148 added−1 removed
Provenance
- Commit
6f4f186- Tree
a950162- Author
Seth Michael Larson <sethmichaellarson@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
33032df
9 files changed+172 added−1 removed
added:docs/environment_variables.md+46 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546Environment Variables=====================
The HTTPX library can be configured via environment variables.Here is a list of environment variables that HTTPX recognizesand what function they serve:
`HTTPX_DEBUG`-----------
Valid values: `1`, `true`
If this environment variable is set to a valid value then low-leveldetails about the execution of HTTP requests will be logged to `stderr`.
This can help you debug issues and see what's exactly being sentover the wire and to which location.
Example:
```python# test_script.py
import httpxclient = httpx.Client()client.get("https://google.com")```
```consoleuser@host:~$ HTTPX_DEBUG=1 python test_script.py20:54:17.585 - httpx.dispatch.connection_pool - acquire_connection origin=Origin(scheme='https' host='www.google.com' port=443)20:54:17.585 - httpx.dispatch.connection_pool - new_connection connection=HTTPConnection(origin=Origin(scheme='https' host='www.google.com' port=443))20:54:17.590 - httpx.dispatch.connection - start_connect host='www.google.com' port=443 timeout=TimeoutConfig(timeout=5.0)20:54:17.651 - httpx.dispatch.connection - connected http_version='HTTP/2'20:54:17.651 - httpx.dispatch.http2 - send_headers stream_id=1 headers=[(b':method', b'GET'), (b':authority', b'www.google.com'), ...]20:54:17.652 - httpx.dispatch.http2 - end_stream stream_id=120:54:17.681 - httpx.dispatch.http2 - receive_event stream_id=0 event=<RemoteSettingsChanged changed_settings:{...}>20:54:17.681 - httpx.dispatch.http2 - receive_event stream_id=0 event=<WindowUpdated stream_id:0, delta:983041>20:54:17.682 - httpx.dispatch.http2 - receive_event stream_id=0 event=<SettingsAcknowledged changed_settings:{}>20:54:17.739 - httpx.dispatch.http2 - receive_event stream_id=1 event=<ResponseReceived stream_id:1, headers:[(b':status', b'200'), ...]>20:54:17.741 - httpx.dispatch.http2 - receive_event stream_id=1 event=<DataReceived stream_id:1, flow_controlled_length:5224 data:>20:54:17.742 - httpx.dispatch.http2 - receive_event stream_id=1 event=<DataReceived stream_id:1, flow_controlled_length:59, data:>20:54:17.742 - httpx.dispatch.http2 - receive_event stream_id=1 event=<StreamEnded stream_id:1>20:54:17.742 - httpx.dispatch.http2 - receive_event stream_id=0 event=<PingReceived ping_data:0000000000000000>20:54:17.743 - httpx.dispatch.connection_pool - release_connection connection=HTTPConnection(origin=Origin(scheme='https' host='www.google.com' port=443))```modified:httpx/dispatch/connection_pool.py+9 added
10 unmodified lines11 TimeoutTypes,12 VerifyTypes,13 )14 from ..models import AsyncRequest, AsyncResponse, Origin15+from ..utils import get_logger16 from .base import AsyncDispatcher17 from .connection import HTTPConnection18 19 CONNECTIONS_DICT = typing.Dict[Origin, typing.List[HTTPConnection]]20 21 22+logger = get_logger(__name__)23+24+25 class ConnectionStore:26 """27 We need to maintain collections of connections in a way that allows us to:28 96 unmodified lines125 126 return response127 128 async def acquire_connection(self, origin: Origin) -> HTTPConnection:129+ logger.debug(f"acquire_connection origin={origin!r}")130 connection = self.active_connections.pop_by_origin(origin, http2_only=True)131 if connection is None:132 connection = self.keepalive_connections.pop_by_origin(origin)133 11 unmodified lines145 http_versions=self.http_versions,146 backend=self.backend,147 release_func=self.release_connection,148 )149+ logger.debug(f"new_connection connection={connection!r}")150+ else:151+ logger.debug(f"reuse_connection connection={connection!r}")152 153 self.active_connections.add(connection)154 155 return connection156 157 async def release_connection(self, connection: HTTPConnection) -> None:158+ logger.debug(f"release_connection connection={connection!r}")159 if connection.is_closed:160 self.active_connections.remove(connection)161 self.max_connections.release()162 elif (16 unmodified linesmodified:httpx/dispatch/connection.py+11 added
13 unmodified lines14 TimeoutTypes,15 VerifyTypes,16 )17 from ..models import AsyncRequest, AsyncResponse, Origin18+from ..utils import get_logger19 from .base import AsyncDispatcher20 from .http2 import HTTP2Connection21 from .http11 import HTTP11Connection22 23 # Callback signature: async def callback(conn: HTTPConnection) -> None24 ReleaseCallback = typing.Callable[["HTTPConnection"], typing.Awaitable[None]]25 26 27+logger = get_logger(__name__)28+29+30 class HTTPConnection(AsyncDispatcher):31 def __init__(32 self,33 origin: typing.Union[str, Origin],48 unmodified lines82 on_release = None83 else:84 on_release = functools.partial(self.release_func, self)85 86+ logger.debug(f"start_connect host={host!r} port={port!r} timeout={timeout!r}")87 stream = await self.backend.connect(host, port, ssl_context, timeout)88 http_version = stream.get_http_version()89+ logger.debug(f"connected http_version={http_version!r}")90 91 if http_version == "HTTP/2":92 self.h2_connection = HTTP2Connection(93 stream, self.backend, on_release=on_release13 unmodified lines107 ssl.load_ssl_context, self.http_versions108 )109 110 async def close(self) -> None:111+ logger.debug("close_connection")112 if self.h2_connection is not None:113 await self.h2_connection.close()114 elif self.h11_connection is not None:115 await self.h11_connection.close()15 unmodified lines131 return self.h2_connection.is_connection_dropped()132 else:133 assert self.h11_connection is not None134 return self.h11_connection.is_connection_dropped()135+136+ def __repr__(self) -> str:137+ class_name = self.__class__.__name__138+ return f"{class_name}(origin={self.origin!r})"modified:httpx/dispatch/http11.py+23 added
3 unmodified lines4 5 from ..concurrency.base import BaseStream, ConcurrencyBackend, TimeoutFlag6 from ..config import TimeoutConfig, TimeoutTypes7 from ..models import AsyncRequest, AsyncResponse8+from ..utils import get_logger9 10 H11Event = typing.Union[11 h11.Request,12 h11.Response,9 unmodified lines22 # the `ConnectionPool.release_connection(conn: HTTPConnection)` method.23 OnReleaseCallback = typing.Callable[[], typing.Awaitable[None]]24 25 26+logger = get_logger(__name__)27+28+29 class HTTP11Connection:30 READ_NUM_BYTES = 409631 32 def __init__(31 unmodified lines64 65 async def close(self) -> None:66 event = h11.ConnectionClosed()67 try:68+ logger.debug(f"send_event event={event!r}")69 self.h11_state.send(event)70 except h11.LocalProtocolError: # pragma: no cover71 # Premature client disconnect72 pass4 unmodified lines77 ) -> None:78 """79 Send the request method, URL, and headers to the network.80 """81+ logger.debug(82+ f"send_headers method={request.method!r} "83+ f"target={request.url.full_path!r} "84+ f"headers={request.headers!r}"85+ )86+87 method = request.method.encode("ascii")88 target = request.url.full_path.encode("ascii")89 headers = request.headers.raw90 event = h11.Request(method=method, target=target, headers=headers)7 unmodified lines98 """99 try:100 # Send the request body.101 async for chunk in data:102+ logger.debug(f"send_data data=Data(<{len(chunk)} bytes>)")103 event = h11.Data(data=chunk)104 await self._send_event(event, timeout)105 106 # Finalize sending the request.54 unmodified lines161 Read a single `h11` event, reading more data from the network if needed.162 """163 while True:164 event = self.h11_state.next_event()165+166+ if isinstance(event, h11.Data):167+ logger.debug(f"receive_event event=Data(<{len(event.data)} bytes>)")168+ else:169+ logger.debug(f"receive_event event={event!r}")170+171 if event is h11.NEED_DATA:172 try:173 data = await self.stream.read(174 self.READ_NUM_BYTES, timeout, flag=self.timeout_flag6 unmodified lines181 break # pragma: no cover182 return event183 184 async def response_closed(self) -> None:185+ logger.debug(186+ f"response_closed "187+ f"our_state={self.h11_state.our_state!r} "188+ f"their_state={self.h11_state.their_state}"189+ )190 if (191 self.h11_state.our_state is h11.DONE192 and self.h11_state.their_state is h11.DONE193 ):15 unmodified linesmodified:httpx/dispatch/http2.py+23 added-1 removed
5 unmodified lines6 7 from ..concurrency.base import BaseStream, ConcurrencyBackend, TimeoutFlag8 from ..config import TimeoutConfig, TimeoutTypes9 from ..models import AsyncRequest, AsyncResponse10+from ..utils import get_logger11 12+logger = get_logger(__name__)13 14+15 class HTTP2Connection:16 READ_NUM_BYTES = 409617 18 def __init__(57 unmodified lines76 (b":authority", request.url.authority.encode("ascii")),77 (b":scheme", request.url.scheme.encode("ascii")),78 (b":path", request.url.full_path.encode("ascii")),79 ] + [(k, v) for k, v in request.headers.raw if k != b"host"]80+81+ logger.debug(82+ f"send_headers "83+ f"stream_id={stream_id} "84+ f"method={request.method!r} "85+ f"target={request.url.full_path!r} "86+ f"headers={headers!r}"87+ )88+89 self.h2_state.send_headers(stream_id, headers)90 data_to_send = self.h2_state.data_to_send()91 await self.stream.write(data_to_send, timeout)92 return stream_id18 unmodified lines111 flow_control = self.h2_state.local_flow_control_window(stream_id)112 chunk_size = min(len(data), flow_control)113 for idx in range(0, len(data), chunk_size):114 chunk = data[idx : idx + chunk_size]115+116+ logger.debug(117+ f"send_data stream_id={stream_id} data=Data(<{len(chunk)} bytes>)"118+ )119+120 self.h2_state.send_data(stream_id, chunk)121 data_to_send = self.h2_state.data_to_send()122 await self.stream.write(data_to_send, timeout)123 124 async def end_stream(self, stream_id: int, timeout: TimeoutConfig = None) -> None:125+ logger.debug(f"end_stream stream_id={stream_id}")126 self.h2_state.end_stream(stream_id)127 data_to_send = self.h2_state.data_to_send()128 await self.stream.write(data_to_send, timeout)129 38 unmodified lines168 flag = self.timeout_flags[stream_id]169 data = await self.stream.read(self.READ_NUM_BYTES, timeout, flag=flag)170 events = self.h2_state.receive_data(data)171 for event in events:154- if getattr(event, "stream_id", 0):172+ event_stream_id = getattr(event, "stream_id", 0)173+ logger.debug(174+ f"receive_event stream_id={event_stream_id} event={event!r}"175+ )176+ if event_stream_id:177 self.events[event.stream_id].append(event)178 179 data_to_send = self.h2_state.data_to_send()180 await self.stream.write(data_to_send, timeout)16 unmodified linesmodified:httpx/models.py+6 added
241 unmodified lines242 243 def __hash__(self) -> int:244 return hash((self.scheme, self.host, self.port))245 246+ def __repr__(self) -> str:247+ class_name = self.__class__.__name__248+ return (249+ f"{class_name}(scheme={self.scheme!r} host={self.host!r} port={self.port})"250+ )251 252+253 class QueryParams(typing.Mapping[str, str]):254 """255 URL query parameters, as a multi-dict.256 """970 unmodified linesmodified:httpx/utils.py+29 added
1 import codecs2+import logging3 import netrc4 import os5 import re6+import sys7 import typing8 from pathlib import Path9 10 130 unmodified lines141 break142 link[key.strip(replace_chars)] = value.strip(replace_chars)143 links.append(link)144 return links145+146+147+_LOGGER_INITIALIZED = False148+149+150+def get_logger(name: str) -> logging.Logger:151+ """Gets a `logging.Logger` instance and optionally152+ sets up debug logging if the user requests it via153+ the `HTTPX_DEBUG=1` environment variable.154+ """155+ global _LOGGER_INITIALIZED156+157+ if not _LOGGER_INITIALIZED:158+ _LOGGER_INITIALIZED = True159+ if os.environ.get("HTTPX_DEBUG", "").lower() in ("1", "true"):160+ logger = logging.getLogger("httpx")161+ logger.setLevel(logging.DEBUG)162+ handler = logging.StreamHandler(sys.stderr)163+ handler.setFormatter(164+ logging.Formatter(165+ fmt="%(asctime)s.%(msecs)03d - %(name)s - %(message)s",166+ datefmt="%H:%M:%S",167+ )168+ )169+ logger.addHandler(handler)170+171+ return logging.getLogger(name)modified:tests/test_utils.py+24 added
1+import logging2 import os3 4 import pytest5 6+import httpx7+from httpx import utils8 from httpx.utils import get_netrc_login, guess_json_utf, parse_header_links9 10 11 @pytest.mark.parametrize(77 unmodified lines89 ),90 )91 def test_parse_header_links(value, expected):92 assert parse_header_links(value) == expected93+94+95+@pytest.mark.asyncio96+@pytest.mark.parametrize("httpx_debug", ["0", "1", "True", "False"])97+async def test_httpx_debug_enabled_stderr_logging(server, capsys, httpx_debug):98+ os.environ["HTTPX_DEBUG"] = httpx_debug99+100+ # Force a reload on the logging handlers101+ utils._LOGGER_INITIALIZED = False102+ utils.get_logger("httpx")103+104+ async with httpx.AsyncClient() as client:105+ await client.get("http://127.0.0.1:8000/")106+107+ if httpx_debug in ("1", "True"):108+ assert "httpx.dispatch.connection_pool" in capsys.readouterr().err109+ else:110+ assert "httpx.dispatch.connection_pool" not in capsys.readouterr().err111+112+ # Reset the logger so we don't have verbose output in all unit tests113+ logging.getLogger("httpx").handlers = []modified:mkdocs.yml+1 added
10 unmodified lines11 nav:12 - Introduction: 'index.md'13 - QuickStart: 'quickstart.md'14 - Advanced Usage: 'advanced.md'15+ - Environment Variables: 'environment_variables.md'16 - Parallel Requests: 'parallel.md'17 - Async Client: 'async.md'18 - Requests Compatibility: 'compatibility.md'19 - Developer Interface: 'api.md'5 unmodified lines