Skip to content
Myr

Use standard logging style (#2547)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Use standard logging style * Add docs for logging * Drop out-of-date HTTPX_LOG_LEVEL variable docs

authored by Tom Christie · committed by GitHub · parent 85c5898 · Browse files · 8 files+158 added−181 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

8 files+158 added−181 removed

  • tests:+50 added−53 removed
  • other:+108 added−128 removed

8 files+158 added−181 removed

modified:docs/environment_variables.md-64 removed
6 unmodified lines
7* Using the top-level API, such as `httpx.get("<url>", trust_env=False)`.89Here is a list of environment variables that HTTPX recognizes and what function they serve:1011## `HTTPX_LOG_LEVEL`1213Valid values: `debug`, `trace` (case-insensitive)1415If set to `debug`, then HTTP requests will be logged to `stderr`. This is useful for general purpose reporting of network activity.1617If 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.1819Example:2021```python22# test_script.py23import httpx2425with httpx.Client() as client:26 r = client.get("https://google.com")27```2829Debug output:3031```console32$ HTTPX_LOG_LEVEL=debug python test_script.py33DEBUG [2019-11-06 19:11:24] httpx._client - HTTP Request: GET https://google.com "HTTP/1.1 301 Moved Permanently"34DEBUG [2019-11-06 19:11:24] httpx._client - HTTP Request: GET https://www.google.com/ "HTTP/1.1 200 OK"35```3637Trace output:3839```console40$ HTTPX_LOG_LEVEL=trace python test_script.py41TRACE [2019-11-06 19:18:56] httpx._dispatch.connection_pool - acquire_connection origin=Origin(scheme='https' host='google.com' port=443)42TRACE [2019-11-06 19:18:56] httpx._dispatch.connection_pool - new_connection connection=HTTPConnection(origin=Origin(scheme='https' host='google.com' port=443))43TRACE [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'])44TRACE [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.pem45TRACE [2019-11-06 19:18:56] httpx._dispatch.connection - start_connect host='google.com' port=443 timeout=Timeout(timeout=5.0)46TRACE [2019-11-06 19:18:56] httpx._dispatch.connection - connected http_version='HTTP/2'47TRACE [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')]48TRACE [2019-11-06 19:18:56] httpx._dispatch.http2 - end_stream stream_id=149TRACE [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)}>50TRACE [2019-11-06 19:18:56] httpx._dispatch.http2 - receive_event stream_id=0 event=<WindowUpdated stream_id:0, delta:983041>51TRACE [2019-11-06 19:18:56] httpx._dispatch.http2 - receive_event stream_id=0 event=<SettingsAcknowledged changed_settings:{}>52TRACE [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')]>53DEBUG [2019-11-06 19:18:56] httpx._client - HTTP Request: GET https://google.com "HTTP/2 301 Moved Permanently"54TRACE [2019-11-06 19:18:56] httpx._dispatch.connection_pool - acquire_connection origin=Origin(scheme='https' host='www.google.com' port=443)55TRACE [2019-11-06 19:18:56] httpx._dispatch.connection_pool - new_connection connection=HTTPConnection(origin=Origin(scheme='https' host='www.google.com' port=443))56TRACE [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'])57TRACE [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.pem58TRACE [2019-11-06 19:18:56] httpx._dispatch.connection - start_connect host='www.google.com' port=443 timeout=Timeout(timeout=5.0)59TRACE [2019-11-06 19:18:56] httpx._dispatch.connection - connected http_version='HTTP/2'60TRACE [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')]61TRACE [2019-11-06 19:18:56] httpx._dispatch.http2 - end_stream stream_id=162TRACE [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)}>63TRACE [2019-11-06 19:18:56] httpx._dispatch.http2 - receive_event stream_id=0 event=<WindowUpdated stream_id:0, delta:983041>64TRACE [2019-11-06 19:18:56] httpx._dispatch.http2 - receive_event stream_id=0 event=<SettingsAcknowledged changed_settings:{}>65TRACE [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')]>66DEBUG [2019-11-06 19:18:56] httpx._client - HTTP Request: GET https://www.google.com/ "HTTP/2 200 OK"67TRACE [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>68TRACE [2019-11-06 19:18:56] httpx._dispatch.http2 - receive_event stream_id=1 event=<DataReceived stream_id:1, flow_controlled_length:221, data:>69TRACE [2019-11-06 19:18:56] httpx._dispatch.http2 - receive_event stream_id=1 event=<StreamEnded stream_id:1>70TRACE [2019-11-06 19:18:56] httpx._dispatch.http2 - receive_event stream_id=0 event=<PingReceived ping_data:0000000000000000>71TRACE [2019-11-06 19:18:56] httpx._dispatch.connection_pool - release_connection connection=HTTPConnection(origin=Origin(scheme='https' host='www.google.com' port=443))72TRACE [2019-11-06 19:18:56] httpx._dispatch.connection - close_connection73```7411## `SSLKEYLOGFILE`1213Valid values: a filename14
99 unmodified lines
added:docs/logging.md+83 added
1# Logging23If you need to inspect the internal behaviour of `httpx`, you can use Python's standard logging to output information about the underlying network behaviour.45For example, the following configuration...67```python8import logging9import httpx1011logging.basicConfig(12 format="%(levelname)s [%(asctime)s] %(name)s - %(message)s",13 datefmt="%Y-%m-%d %H:%M:%S",14 level=logging.DEBUG15)1617httpx.get("https://www.example.com")18```1920Will send debug level output to the console, or wherever `stdout` is directed too...2122```23DEBUG [2023-03-16 14:36:20] httpx - load_ssl_context verify=True cert=None trust_env=True http2=False24DEBUG [2023-03-16 14:36:20] httpx - load_verify_locations cafile='/Users/tomchristie/GitHub/encode/httpx/venv/lib/python3.10/site-packages/certifi/cacert.pem'25DEBUG [2023-03-16 14:36:20] httpcore - connection.connect_tcp.started host='www.example.com' port=443 local_address=None timeout=5.026DEBUG [2023-03-16 14:36:20] httpcore - connection.connect_tcp.complete return_value=<httpcore.backends.sync.SyncStream object at 0x1068fd270>27DEBUG [2023-03-16 14:36:20] httpcore - connection.start_tls.started ssl_context=<ssl.SSLContext object at 0x10689aa40> server_hostname='www.example.com' timeout=5.028DEBUG [2023-03-16 14:36:20] httpcore - connection.start_tls.complete return_value=<httpcore.backends.sync.SyncStream object at 0x1068fd240>29DEBUG [2023-03-16 14:36:20] httpcore - http11.send_request_headers.started request=<Request [b'GET']>30DEBUG [2023-03-16 14:36:20] httpcore - http11.send_request_headers.complete31DEBUG [2023-03-16 14:36:20] httpcore - http11.send_request_body.started request=<Request [b'GET']>32DEBUG [2023-03-16 14:36:20] httpcore - http11.send_request_body.complete33DEBUG [2023-03-16 14:36:20] httpcore - http11.receive_response_headers.started request=<Request [b'GET']>34DEBUG [2023-03-16 14:36:21] httpcore - http11.receive_response_headers.complete return_value=(b'HTTP/1.1', 200, b'OK', [(b'Content-Encoding', b'gzip'), (b'Accept-Ranges', b'bytes'), (b'Age', b'507675'), (b'Cache-Control', b'max-age=604800'), (b'Content-Type', b'text/html; charset=UTF-8'), (b'Date', b'Thu, 16 Mar 2023 14:36:21 GMT'), (b'Etag', b'"3147526947+ident"'), (b'Expires', b'Thu, 23 Mar 2023 14:36:21 GMT'), (b'Last-Modified', b'Thu, 17 Oct 2019 07:18:26 GMT'), (b'Server', b'ECS (nyb/1D2E)'), (b'Vary', b'Accept-Encoding'), (b'X-Cache', b'HIT'), (b'Content-Length', b'648')])35INFO [2023-03-16 14:36:21] httpx - HTTP Request: GET https://www.example.com "HTTP/1.1 200 OK"36DEBUG [2023-03-16 14:36:21] httpcore - http11.receive_response_body.started request=<Request [b'GET']>37DEBUG [2023-03-16 14:36:21] httpcore - http11.receive_response_body.complete38DEBUG [2023-03-16 14:36:21] httpcore - http11.response_closed.started39DEBUG [2023-03-16 14:36:21] httpcore - http11.response_closed.complete40DEBUG [2023-03-16 14:36:21] httpcore - connection.close.started41DEBUG [2023-03-16 14:36:21] httpcore - connection.close.complete42```4344Logging output includes information from both the high-level `httpx` logger, and the network-level `httpcore` logger, which can be configured seperately.4546For handling more complex logging configurations you might want to use the dictionary configuration style...4748```python49import logging.config50import httpx5152LOGGING_CONFIG = {53 "version": 1,54 "handlers": {55 "default": {56 "class": "logging.StreamHandler",57 "formatter": "http",58 "stream": "ext://sys.stderr"59 }60 },61 "formatters": {62 "http": {63 "format": "%(levelname)s [%(asctime)s] %(name)s - %(message)s",64 "datefmt": "%Y-%m-%d %H:%M:%S",65 }66 },67 'loggers': {68 'httpx': {69 'handlers': ['default'],70 'level': 'DEBUG',71 },72 'httpcore': {73 'handlers': ['default'],74 'level': 'DEBUG',75 },76 }77}7879logging.config.dictConfig(LOGGING_CONFIG)80httpx.get('https://www.example.com')81```8283The exact formatting of the debug logging may be subject to change across different versions of `httpx` and `httpcore`. If you need to rely on a particular format it is recommended that you pin installation of these packages to fixed versions.
modified:httpx/_client.py+9 added-6 removed
1import datetime2import enum3import logging4import typing5import warnings6from contextlib import asynccontextmanager, contextmanager7from types import TracebackType
42 unmodified lines
50from ._utils import (51 Timer,52 URLPattern,53 get_environment_proxies,53 get_logger,54 is_https_redirect,55 same_origin,56)57
25 unmodified lines
8384USE_CLIENT_DEFAULT = UseClientDefault()858687logger = get_logger(__name__)87logger = logging.getLogger("httpx")8889USER_AGENT = f"python-httpx/{__version__}"90ACCEPT_ENCODING = ", ".join(91 [key for key in SUPPORTED_DECODERS.keys() if key != "identity"]
917 unmodified lines
1009 )1010 self.cookies.extract_cookies(response)1011 response.default_encoding = self._default_encoding10121013 status = f"{response.status_code} {response.reason_phrase}"1014 response_line = f"{response.http_version} {status}"1015 logger.debug(1016 'HTTP Request: %s %s "%s"', request.method, request.url, response_line1013 logger.info(1014 'HTTP Request: %s %s "%s %d %s"',1015 request.method,1016 request.url,1017 response.http_version,1018 response.status_code,1019 response.reason_phrase,1020 )10211022 return response1023
980 unmodified lines
modified:httpx/_config.py+15 added-12 removed
1import logging2import os3import ssl4import sys5import typing
4 unmodified lines
10from ._compat import set_minimum_tls_version_1_211from ._models import Headers12from ._types import CertTypes, HeaderTypes, TimeoutTypes, URLTypes, VerifyTypes13from ._urls import URL13from ._utils import get_ca_bundle_from_env, get_logger14from ._utils import get_ca_bundle_from_env1516DEFAULT_CIPHERS = ":".join(17 [18 "ECDHE+AESGCM",
13 unmodified lines
32 ]33)343535logger = get_logger(__name__)36logger = logging.getLogger("httpx")373839class UnsetType:40 pass # pragma: no cover
34 unmodified lines
75 self.http2 = http276 self.ssl_context = self.load_ssl_context()7778 def load_ssl_context(self) -> ssl.SSLContext:78 logger.trace(79 f"load_ssl_context "80 f"verify={self.verify!r} "81 f"cert={self.cert!r} "82 f"trust_env={self.trust_env!r} "83 f"http2={self.http2!r}"79 logger.debug(80 "load_ssl_context verify=%r cert=%r trust_env=%r http2=%r",81 self.verify,82 self.cert,83 self.trust_env,84 self.http2,85 )8687 if self.verify:88 return self.load_ssl_context_verify()
52 unmodified lines
141 except AttributeError: # pragma: no cover142 pass143144 if ca_bundle_path.is_file():144 logger.trace(f"load_verify_locations cafile={ca_bundle_path!s}")145 context.load_verify_locations(cafile=str(ca_bundle_path))145 cafile = str(ca_bundle_path)146 logger.debug("load_verify_locations cafile=%r", cafile)147 context.load_verify_locations(cafile=cafile)148 elif ca_bundle_path.is_dir():147 logger.trace(f"load_verify_locations capath={ca_bundle_path!s}")148 context.load_verify_locations(capath=str(ca_bundle_path))149 capath = str(ca_bundle_path)150 logger.debug("load_verify_locations capath=%r", capath)151 context.load_verify_locations(capath=capath)152153 self._load_client_certs(context)154155 return context
214 unmodified lines
modified:httpx/_utils.py-46 removed
1import codecs2import email.message3import logging3import mimetypes4import os5import re7import sys6import time7import typing8from pathlib import Path9from urllib.request import getproxies
183 unmodified lines
193 v = to_bytes_or_str("[secure]", match_type_of=v)194 yield k, v195196199_LOGGER_INITIALIZED = False200TRACE_LOG_LEVEL = 5201202203class Logger(logging.Logger):204 # Stub for type checkers.205 def trace(self, message: str, *args: typing.Any, **kwargs: typing.Any) -> None:206 ... # pragma: no cover207208209def get_logger(name: str) -> Logger:210 """211 Get a `logging.Logger` instance, and optionally212 set up debug logging based on the HTTPX_LOG_LEVEL environment variable.213 """214 global _LOGGER_INITIALIZED215216 if not _LOGGER_INITIALIZED:217 _LOGGER_INITIALIZED = True218 logging.addLevelName(TRACE_LOG_LEVEL, "TRACE")219220 log_level = os.environ.get("HTTPX_LOG_LEVEL", "").upper()221 if log_level in ("DEBUG", "TRACE"):222 logger = logging.getLogger("httpx")223 logger.setLevel(logging.DEBUG if log_level == "DEBUG" else TRACE_LOG_LEVEL)224 handler = logging.StreamHandler(sys.stderr)225 handler.setFormatter(226 logging.Formatter(227 fmt="%(levelname)s [%(asctime)s] %(name)s - %(message)s",228 datefmt="%Y-%m-%d %H:%M:%S",229 )230 )231 logger.addHandler(handler)232233 logger = logging.getLogger(name)234235 def trace(message: str, *args: typing.Any, **kwargs: typing.Any) -> None:236 logger.log(TRACE_LOG_LEVEL, message, *args, **kwargs)237238 logger.trace = trace # type: ignore239240 return typing.cast(Logger, logger)241242197def port_or_default(url: "URL") -> typing.Optional[int]:198 if url.port is not None:199 return url.port200 return {"http": 80, "https": 443}.get(url.scheme)
251 unmodified lines
modified:tests/test_utils.py+50 added-32 removed
1import logging2import os3import random45import certifi6import pytest78import httpx9from httpx._utils import (
5 unmodified lines
15 obfuscate_sensitive_headers,16 parse_header_links,17 same_origin,18)17from tests.utils import override_log_level1920from .common import TESTS_DIR2122
55 unmodified lines
78def test_parse_header_links(value, expected):79 assert parse_header_links(value) == expected808181@pytest.mark.anyio82async def test_logs_debug(server, capsys):83 with override_log_level("debug"):84 async with httpx.AsyncClient() as client:85 response = await client.get(server.url)86 assert response.status_code == 20087 stderr = capsys.readouterr().err88 assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr82def test_logging_request(server, caplog):83 caplog.set_level(logging.INFO)84 with httpx.Client() as client:85 response = client.get(server.url)86 assert response.status_code == 2008788 assert caplog.record_tuples == [89 (90 "httpx",91 logging.INFO,92 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"',93 )94 ]9591@pytest.mark.anyio92async def test_logs_trace(server, capsys):93 with override_log_level("trace"):94 async with httpx.AsyncClient() as client:95 response = await client.get(server.url)96 assert response.status_code == 20097 stderr = capsys.readouterr().err98 assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr9697def test_logging_redirect_chain(server, caplog):98 caplog.set_level(logging.INFO)99 with httpx.Client(follow_redirects=True) as client:100 response = client.get(server.url.copy_with(path="/redirect_301"))101 assert response.status_code == 200102101@pytest.mark.anyio102async def test_logs_redirect_chain(server, capsys):103 with override_log_level("debug"):104 async with httpx.AsyncClient(follow_redirects=True) as client:105 response = await client.get(server.url.copy_with(path="/redirect_301"))106 assert response.status_code == 200103 assert caplog.record_tuples == [104 (105 "httpx",106 logging.INFO,107 'HTTP Request: GET http://127.0.0.1:8000/redirect_301 "HTTP/1.1 301 Moved Permanently"',108 ),109 (110 "httpx",111 logging.INFO,112 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"',113 ),114 ]115108 stderr = capsys.readouterr().err.strip()109 redirected_request_line, ok_request_line = stderr.split("\n")110 assert redirected_request_line.endswith(111 "HTTP Request: GET http://127.0.0.1:8000/redirect_301 "112 '"HTTP/1.1 301 Moved Permanently"'113 )114 assert ok_request_line.endswith(115 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"'116 )116117def test_logging_ssl(caplog):118 caplog.set_level(logging.DEBUG)119 with httpx.Client():120 pass121122 cafile = certifi.where()123 assert caplog.record_tuples == [124 (125 "httpx",126 logging.DEBUG,127 "load_ssl_context verify=True cert=None trust_env=True http2=False",128 ),129 (130 "httpx",131 logging.DEBUG,132 f"load_verify_locations cafile='{cafile}'",133 ),134 ]135136137def test_get_ssl_cert_file():138 # Two environments is not set.139 assert get_ca_bundle_from_env() is None140
136 unmodified lines
deleted:tests/utils.py-21 removed
1import contextlib2import logging3import os4import typing56from httpx import _utils789@contextlib.contextmanager10def override_log_level(log_level: str) -> typing.Iterator[None]:11 os.environ["HTTPX_LOG_LEVEL"] = log_level1213 # Force a reload on the logging handlers14 _utils._LOGGER_INITIALIZED = False15 _utils.get_logger("httpx")1617 try:18 yield19 finally:20 # Reset the logger so we don't have verbose output in all unit tests21 logging.getLogger("httpx").handlers = []
modified:mkdocs.yml+1 added