Convert debug logs to trace logs (#500)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Convert debug logs to trace logs * Update environment variables docs * Update logging test
authored by Florimond Manca · committed by GitHub · parent 717b341 · Browse files · 9 files·+63 added−49 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+63 added−49 removed
- tests:+4 added−4 removed
- other:+59 added−45 removed
Provenance
- Commit
07586f9- Tree
a259cb2- Author
Florimond Manca <florimond.manca@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
717b341
9 files changed+63 added−49 removed
modified:docs/environment_variables.md+6 added-8 removed
9 unmodified lines10111213141514151617171819201920222321222324254 unmodified lines3031323336343536373891 unmodified lines9 unmodified lines
Here is a list of environment variables that HTTPX recognizesand what function they serve:
`HTTPX_DEBUG`-----------`HTTPX_LOG_LEVEL`-----------------
Valid values: `1`, `true`Valid values: `debug`, `trace` (case-insensitive)
If this environment variable is set to a valid value then low-leveldetails about the execution of HTTP requests will be logged to `stderr`.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.
This can help you debug issues and see what's exactly being sentover the wire and to which location.The `debug` log level is currently ignored, but is planned to issue high-level logs of HTTP requests.
Example:
```python4 unmodified lines r = client.get("https://google.com")```
```consoleuser@host:~$ HTTPX_DEBUG=1 python test_script.pyuser@host:~$ HTTPX_LOG_LEVEL=trace 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'91 unmodified linesmodified:httpx/dispatch/connection_pool.py+4 added-4 removed
126 unmodified lines127 128 return response129 130 async def acquire_connection(self, origin: Origin) -> HTTPConnection:131- logger.debug(f"acquire_connection origin={origin!r}")131+ logger.trace(f"acquire_connection origin={origin!r}")132 connection = self.pop_connection(origin)133 134 if connection is None:135 await self.max_connections.acquire()6 unmodified lines142 backend=self.backend,143 release_func=self.release_connection,144 trust_env=self.trust_env,145 )146- logger.debug(f"new_connection connection={connection!r}")146+ logger.trace(f"new_connection connection={connection!r}")147 else:148- logger.debug(f"reuse_connection connection={connection!r}")148+ logger.trace(f"reuse_connection connection={connection!r}")149 150 self.active_connections.add(connection)151 152 return connection153 154 async def release_connection(self, connection: HTTPConnection) -> None:155- logger.debug(f"release_connection connection={connection!r}")155+ logger.trace(f"release_connection connection={connection!r}")156 if connection.is_closed:157 self.active_connections.remove(connection)158 self.max_connections.release()159 elif (27 unmodified linesmodified:httpx/dispatch/connection.py+3 added-3 removed
82 unmodified lines83 on_release = None84 else:85 on_release = functools.partial(self.release_func, self)86 87- logger.debug(f"start_connect host={host!r} port={port!r} timeout={timeout!r}")87+ logger.trace(f"start_connect host={host!r} port={port!r} timeout={timeout!r}")88 stream = await self.backend.open_tcp_stream(host, port, ssl_context, timeout)89 http_version = stream.get_http_version()90- logger.debug(f"connected http_version={http_version!r}")90+ logger.trace(f"connected http_version={http_version!r}")91 92 if http_version == "HTTP/2":93 self.h2_connection = HTTP2Connection(94 stream, self.backend, on_release=on_release13 unmodified lines108 ssl.load_ssl_context, self.http_versions109 )110 111 async def close(self) -> None:112- logger.debug("close_connection")112+ logger.trace("close_connection")113 if self.h2_connection is not None:114 await self.h2_connection.close()115 elif self.h11_connection is not None:116 await self.h11_connection.close()23 unmodified linesmodified:httpx/dispatch/http11.py+6 added-6 removed
63 unmodified lines64 65 async def close(self) -> None:66 event = h11.ConnectionClosed()67 try:68- logger.debug(f"send_event event={event!r}")68+ logger.trace(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(81+ logger.trace(82 f"send_headers method={request.method!r} "83 f"target={request.url.full_path!r} "84 f"headers={request.headers!r}"85 )12 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>)")102+ logger.trace(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.56 unmodified lines163 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>)")167+ logger.trace(f"receive_event event=Data(<{len(event.data)} bytes>)")168 else:169- logger.debug(f"receive_event event={event!r}")169+ logger.trace(f"receive_event event={event!r}")170 171 if event is h11.NEED_DATA:172 try:173 data = await self.stream.read(7 unmodified lines181 break # pragma: no cover182 return event183 184 async def response_closed(self) -> None:185- logger.debug(185+ logger.trace(186 f"response_closed "187 f"our_state={self.h11_state.our_state!r} "188 f"their_state={self.h11_state.their_state}"189 )19 unmodified linesmodified:httpx/dispatch/http2.py+3 added-3 removed
102 unmodified lines103 (b":scheme", request.url.scheme.encode("ascii")),104 (b":path", request.url.full_path.encode("ascii")),105 ] + [(k, v) for k, v in request.headers.raw if k != b"host"]106 107- logger.debug(107+ logger.trace(108 f"send_headers "109 f"stream_id={stream_id} "110 f"method={request.method!r} "111 f"target={request.url.full_path!r} "43 unmodified lines155 data_to_send = self.h2_state.data_to_send()156 await self.stream.write(data_to_send, timeout)157 158 async def end_stream(self, stream_id: int, timeout: TimeoutConfig = None) -> None:159- logger.debug(f"end_stream stream_id={stream_id}")159+ logger.trace(f"end_stream stream_id={stream_id}")160 self.h2_state.end_stream(stream_id)161 data_to_send = self.h2_state.data_to_send()162 await self.stream.write(data_to_send, timeout)163 42 unmodified lines206 data = await self.stream.read(self.READ_NUM_BYTES, timeout, flag=flag)207 events = self.h2_state.receive_data(data)208 for event in events:209 event_stream_id = getattr(event, "stream_id", 0)210- logger.debug(210+ logger.trace(211 f"receive_event stream_id={event_stream_id} event={event!r}"212 )213 214 if hasattr(event, "error_code"):37 unmodified linesmodified:httpx/dispatch/proxy_http.py+5 added-5 removed
84 unmodified lines85 self.proxy_url = url.copy_with(authority=authority)86 87 async def acquire_connection(self, origin: Origin) -> HTTPConnection:88 if self.should_forward_origin(origin):89- logger.debug(89+ logger.trace(90 f"forward_connection proxy_url={self.proxy_url!r} origin={origin!r}"91 )92 return await super().acquire_connection(self.proxy_url.origin)93 else:94- logger.debug(94+ logger.trace(95 f"tunnel_connection proxy_url={self.proxy_url!r} origin={origin!r}"96 )97 return await self.tunnel_connection(origin)98 43 unmodified lines142 self.active_connections.add(connection)143 144 # See if our tunnel has been opened successfully145 proxy_response = await connection.send(proxy_request)146- logger.debug(146+ logger.trace(147 f"tunnel_response "148 f"proxy_url={self.proxy_url!r} "149 f"origin={origin!r} "150 f"response={proxy_response!r}"35 unmodified lines186 timeout = connection.timeout187 ssl_context = await connection.get_ssl_context(ssl_config)188 assert ssl_context is not None189 190- logger.debug(190+ logger.trace(191 f"tunnel_start_tls "192 f"proxy_url={self.proxy_url!r} "193 f"origin={origin!r}"194 )195 stream = await stream.start_tls(196 hostname=origin.host, ssl_context=ssl_context, timeout=timeout197 )198 http_version = stream.get_http_version()199- logger.debug(199+ logger.trace(200 f"tunnel_tls_complete "201 f"proxy_url={self.proxy_url!r} "202 f"origin={origin!r} "203 f"http_version={http_version!r}"50 unmodified linesmodified:httpx/config.py+3 added-3 removed
92 unmodified lines93 self, http_versions: "HTTPVersionConfig" = None94 ) -> ssl.SSLContext:95 http_versions = HTTPVersionConfig() if http_versions is None else http_versions96 97- logger.debug(97+ logger.trace(98 f"load_ssl_context "99 f"verify={self.verify!r} "100 f"cert={self.cert!r} "101 f"trust_env={self.trust_env!r} "60 unmodified lines162 except AttributeError: # pragma: nocover163 pass164 165 if ca_bundle_path.is_file():166- logger.debug(f"load_verify_locations cafile={ca_bundle_path!s}")166+ logger.trace(f"load_verify_locations cafile={ca_bundle_path!s}")167 context.load_verify_locations(cafile=str(ca_bundle_path))168 elif ca_bundle_path.is_dir():169- logger.debug(f"load_verify_locations capath={ca_bundle_path!s}")169+ logger.trace(f"load_verify_locations capath={ca_bundle_path!s}")170 context.load_verify_locations(capath=str(ca_bundle_path))171 172 self._load_client_certs(context)173 180 unmodified linesmodified:httpx/utils.py+29 added-13 removed
174 unmodified lines175 yield k, v176 177 178 _LOGGER_INITIALIZED = False179+TRACE_LOG_LEVEL = 5180 181 181-def get_logger(name: str) -> logging.Logger:182- """Gets a `logging.Logger` instance and optionally183- sets up debug logging if the user requests it via184- the `HTTPX_DEBUG=1` environment variable.182+class Logger(logging.Logger):183+ # Stub for type checkers.184+ def trace(self, message: str, *args: typing.Any, **kwargs: typing.Any) -> None:185+ ...186+187+188+def get_logger(name: str) -> Logger:189 """190+ Get a `logging.Logger` instance, and optionally191+ set up debug logging based on the HTTPX_LOG_LEVEL environment variable.192+ """193 global _LOGGER_INITIALIZED194 195 if not _LOGGER_INITIALIZED:196 _LOGGER_INITIALIZED = True190- if os.environ.get("HTTPX_DEBUG", "").lower() in ("1", "true"):197+198+ log_level = os.environ.get("HTTPX_LOG_LEVEL", "").upper()199+ if log_level in ("DEBUG", "TRACE"):200 logger = logging.getLogger("httpx")192- logger.setLevel(logging.DEBUG)201+ logger.setLevel(logging.DEBUG if log_level == "DEBUG" else TRACE_LOG_LEVEL)202 handler = logging.StreamHandler(sys.stderr)203 handler.setFormatter(204 logging.Formatter(205 fmt="%(asctime)s.%(msecs)03d - %(name)s - %(message)s",1 unmodified line207 )208 )209 logger.addHandler(handler)210 202- return logging.getLogger(name)211+ logger = logging.getLogger(name)212 213+ def trace(message: str, *args: typing.Any, **kwargs: typing.Any) -> None:214+ logger.log(TRACE_LOG_LEVEL, message, *args, **kwargs)215 216+ logger.trace = trace # type: ignore217+218+ return typing.cast(Logger, logger)219+220+221 def kv_format(**kwargs: typing.Any) -> str:222 """Format arguments into a key=value line.223 224 >>> formatkv(x=1, name="Bob")130 unmodified lines355 return new_message356 357 358 class MessageLoggerASGIMiddleware:343- def __init__(self, app: typing.Callable, logger: logging.Logger) -> None:359+ def __init__(self, app: typing.Callable, logger: Logger) -> None:360 self.app = app361 self.logger = logger362 363 async def __call__(1 unmodified line365 ) -> None:366 async def inner_receive() -> dict:367 message = await receive()368 logged_message = asgi_message_with_placeholders(message)353- self.logger.debug(f"sent {kv_format(**logged_message)}")369+ self.logger.trace(f"sent {kv_format(**logged_message)}")370 return message371 372 async def inner_send(message: dict) -> None:373 logged_message = asgi_message_with_placeholders(message)358- self.logger.debug(f"received {kv_format(**logged_message)}")374+ self.logger.trace(f"received {kv_format(**logged_message)}")375 await send(message)376 377 logged_scope = dict(scope)378 if "headers" in scope:379 logged_scope["headers"] = list(380 obfuscate_sensitive_headers(scope["headers"])381 )366- self.logger.debug(f"started {kv_format(**logged_scope)}")382+ self.logger.trace(f"started {kv_format(**logged_scope)}")383 384 try:385 await self.app(scope, inner_receive, inner_send)386 except BaseException as exc:371- self.logger.debug("raised_exception")387+ self.logger.trace("raised_exception")388 raise exc from None389 else:374- self.logger.debug("completed")390+ self.logger.trace("completed")modified:tests/test_utils.py+4 added-4 removed
101 unmodified lines102 assert parse_header_links(value) == expected103 104 105 @pytest.mark.asyncio106-@pytest.mark.parametrize("httpx_debug", ["0", "1", "True", "False"])107-async def test_httpx_debug_enabled_stderr_logging(server, capsys, httpx_debug):108- os.environ["HTTPX_DEBUG"] = httpx_debug106+@pytest.mark.parametrize("httpx_log_level", ["trace", "debug"])107+async def test_httpx_log_level_enabled_stderr_logging(server, capsys, httpx_log_level):108+ os.environ["HTTPX_LOG_LEVEL"] = httpx_log_level109 110 # Force a reload on the logging handlers111 utils._LOGGER_INITIALIZED = False112 utils.get_logger("httpx")113 114 async with httpx.AsyncClient() as client:115 await client.get(server.url)116 117- if httpx_debug in ("1", "True"):117+ if httpx_log_level == "trace":118 assert "httpx.dispatch.connection_pool" in capsys.readouterr().err119 else:120 assert "httpx.dispatch.connection_pool" not in capsys.readouterr().err121 159 unmodified lines