Skip to content
Myr

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

9 files+63 added−49 removed

modified:docs/environment_variables.md+6 added-8 removed
modified:httpx/dispatch/connection_pool.py+4 added-4 removed
126 unmodified lines
127128 return response129130 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)133134 if connection is None:135 await self.max_connections.acquire()
6 unmodified lines
142 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}")149150 self.active_connections.add(connection)151152 return connection153154 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 lines
modified:httpx/dispatch/connection.py+3 added-3 removed
82 unmodified lines
83 on_release = None84 else:85 on_release = functools.partial(self.release_func, self)8687 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}")9192 if http_version == "HTTP/2":93 self.h2_connection = HTTP2Connection(94 stream, self.backend, on_release=on_release
13 unmodified lines
108 ssl.load_ssl_context, self.http_versions109 )110111 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 lines
modified:httpx/dispatch/http11.py+6 added-6 removed
63 unmodified lines
6465 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 pass
4 unmodified lines
77 ) -> 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 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>)")102 logger.trace(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.
56 unmodified lines
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>)")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}")170171 if event is h11.NEED_DATA:172 try:173 data = await self.stream.read(
7 unmodified lines
181 break # pragma: no cover182 return event183184 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 lines
modified:httpx/dispatch/http2.py+3 added-3 removed
102 unmodified lines
103 (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"]106107 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 lines
155 data_to_send = self.h2_state.data_to_send()156 await self.stream.write(data_to_send, timeout)157158 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 lines
206 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 )213214 if hasattr(event, "error_code"):
37 unmodified lines
modified:httpx/dispatch/proxy_http.py+5 added-5 removed
84 unmodified lines
85 self.proxy_url = url.copy_with(authority=authority)8687 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 lines
142 self.active_connections.add(connection)143144 # 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 lines
186 timeout = connection.timeout187 ssl_context = await connection.get_ssl_context(ssl_config)188 assert ssl_context is not None189190 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 lines
modified:httpx/config.py+3 added-3 removed
92 unmodified lines
93 self, http_versions: "HTTPVersionConfig" = None94 ) -> ssl.SSLContext:95 http_versions = HTTPVersionConfig() if http_versions is None else http_versions9697 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 lines
162 except AttributeError: # pragma: nocover163 pass164165 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))171172 self._load_client_certs(context)173
180 unmodified lines
modified:httpx/utils.py+29 added-13 removed
174 unmodified lines
175 yield k, v176177178_LOGGER_INITIALIZED = False179TRACE_LOG_LEVEL = 5180181181def 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.182class Logger(logging.Logger):183 # Stub for type checkers.184 def trace(self, message: str, *args: typing.Any, **kwargs: typing.Any) -> None:185 ...186187188def 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_INITIALIZED194195 if not _LOGGER_INITIALIZED:196 _LOGGER_INITIALIZED = True190 if os.environ.get("HTTPX_DEBUG", "").lower() in ("1", "true"):197198 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 line
207 )208 )209 logger.addHandler(handler)210202 return logging.getLogger(name)211 logger = logging.getLogger(name)212213 def trace(message: str, *args: typing.Any, **kwargs: typing.Any) -> None:214 logger.log(TRACE_LOG_LEVEL, message, *args, **kwargs)215216 logger.trace = trace # type: ignore217218 return typing.cast(Logger, logger)219220221def kv_format(**kwargs: typing.Any) -> str:222 """Format arguments into a key=value line.223224 >>> formatkv(x=1, name="Bob")
130 unmodified lines
355 return new_message356357358class 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 = logger362363 async def __call__(
1 unmodified line
365 ) -> 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 message371372 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)376377 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)}")383384 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 lines
102 assert parse_header_links(value) == expected103104105@pytest.mark.asyncio106@pytest.mark.parametrize("httpx_debug", ["0", "1", "True", "False"])107async 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"])107async def test_httpx_log_level_enabled_stderr_logging(server, capsys, httpx_log_level):108 os.environ["HTTPX_LOG_LEVEL"] = httpx_log_level109110 # Force a reload on the logging handlers111 utils._LOGGER_INITIALIZED = False112 utils.get_logger("httpx")113114 async with httpx.AsyncClient() as client:115 await client.get(server.url)116117 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