Skip to content
Myr

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

9 files+172 added−1 removed

added:docs/environment_variables.md+46 added
modified:httpx/dispatch/connection_pool.py+9 added
10 unmodified lines
11 TimeoutTypes,12 VerifyTypes,13)14from ..models import AsyncRequest, AsyncResponse, Origin15from ..utils import get_logger16from .base import AsyncDispatcher17from .connection import HTTPConnection1819CONNECTIONS_DICT = typing.Dict[Origin, typing.List[HTTPConnection]]202122logger = get_logger(__name__)232425class ConnectionStore:26 """27 We need to maintain collections of connections in a way that allows us to:28
96 unmodified lines
125126 return response127128 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 lines
145 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}")152153 self.active_connections.add(connection)154155 return connection156157 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 lines
modified:httpx/dispatch/connection.py+11 added
13 unmodified lines
14 TimeoutTypes,15 VerifyTypes,16)17from ..models import AsyncRequest, AsyncResponse, Origin18from ..utils import get_logger19from .base import AsyncDispatcher20from .http2 import HTTP2Connection21from .http11 import HTTP11Connection2223# Callback signature: async def callback(conn: HTTPConnection) -> None24ReleaseCallback = typing.Callable[["HTTPConnection"], typing.Awaitable[None]]252627logger = get_logger(__name__)282930class HTTPConnection(AsyncDispatcher):31 def __init__(32 self,33 origin: typing.Union[str, Origin],
48 unmodified lines
82 on_release = None83 else:84 on_release = functools.partial(self.release_func, self)8586 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}")9091 if http_version == "HTTP/2":92 self.h2_connection = HTTP2Connection(93 stream, self.backend, on_release=on_release
13 unmodified lines
107 ssl.load_ssl_context, self.http_versions108 )109110 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 lines
131 return self.h2_connection.is_connection_dropped()132 else:133 assert self.h11_connection is not None134 return self.h11_connection.is_connection_dropped()135136 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 lines
45from ..concurrency.base import BaseStream, ConcurrencyBackend, TimeoutFlag6from ..config import TimeoutConfig, TimeoutTypes7from ..models import AsyncRequest, AsyncResponse8from ..utils import get_logger910H11Event = typing.Union[11 h11.Request,12 h11.Response,
9 unmodified lines
22# the `ConnectionPool.release_connection(conn: HTTPConnection)` method.23OnReleaseCallback = typing.Callable[[], typing.Awaitable[None]]242526logger = get_logger(__name__)272829class HTTP11Connection:30 READ_NUM_BYTES = 40963132 def __init__(
31 unmodified lines
6465 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 pass
4 unmodified lines
77 ) -> 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 )8687 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 lines
98 """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)105106 # Finalize sending the request.
54 unmodified lines
161 Read a single `h11` event, reading more data from the network if needed.162 """163 while True:164 event = self.h11_state.next_event()165166 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}")170171 if event is h11.NEED_DATA:172 try:173 data = await self.stream.read(174 self.READ_NUM_BYTES, timeout, flag=self.timeout_flag
6 unmodified lines
181 break # pragma: no cover182 return event183184 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 lines
modified:httpx/dispatch/http2.py+23 added-1 removed
5 unmodified lines
67from ..concurrency.base import BaseStream, ConcurrencyBackend, TimeoutFlag8from ..config import TimeoutConfig, TimeoutTypes9from ..models import AsyncRequest, AsyncResponse10from ..utils import get_logger1112logger = get_logger(__name__)131415class HTTP2Connection:16 READ_NUM_BYTES = 40961718 def __init__(
57 unmodified lines
76 (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"]8081 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 )8889 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_id
18 unmodified lines
111 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]115116 logger.debug(117 f"send_data stream_id={stream_id} data=Data(<{len(chunk)} bytes>)"118 )119120 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)123124 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 lines
168 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)178179 data_to_send = self.h2_state.data_to_send()180 await self.stream.write(data_to_send, timeout)
16 unmodified lines
modified:httpx/models.py+6 added
241 unmodified lines
242243 def __hash__(self) -> int:244 return hash((self.scheme, self.host, self.port))245246 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 )251252253class QueryParams(typing.Mapping[str, str]):254 """255 URL query parameters, as a multi-dict.256 """
970 unmodified lines
modified:httpx/utils.py+29 added
1import codecs2import logging3import netrc4import os5import re6import sys7import typing8from pathlib import Path910
130 unmodified lines
141 break142 link[key.strip(replace_chars)] = value.strip(replace_chars)143 links.append(link)144 return links145146147_LOGGER_INITIALIZED = False148149150def 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_INITIALIZED156157 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)170171 return logging.getLogger(name)
modified:tests/test_utils.py+24 added
1import logging2import os34import pytest56import httpx7from httpx import utils8from httpx.utils import get_netrc_login, guess_json_utf, parse_header_links91011@pytest.mark.parametrize(
77 unmodified lines
89 ),90)91def test_parse_header_links(value, expected):92 assert parse_header_links(value) == expected939495@pytest.mark.asyncio96@pytest.mark.parametrize("httpx_debug", ["0", "1", "True", "False"])97async def test_httpx_debug_enabled_stderr_logging(server, capsys, httpx_debug):98 os.environ["HTTPX_DEBUG"] = httpx_debug99100 # Force a reload on the logging handlers101 utils._LOGGER_INITIALIZED = False102 utils.get_logger("httpx")103104 async with httpx.AsyncClient() as client:105 await client.get("http://127.0.0.1:8000/")106107 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().err111112 # 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 lines
11nav: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