Logging all wire communication (request & response) #3492
Replies: 2 comments
|
import httpx
def log_request(request: httpx.Request) -> None:
print("-->", request.method, request.url)
print(" headers:", request.headers)
print(" body:", request.content)
def log_response(response: httpx.Response) -> None:
response.read() # required — see below
print("<--", response.status_code, response.url)
print(" headers:", response.headers)
print(" body:", response.content)
return response
client = httpx.Client(event_hooks={
"request": [log_request],
"response": [log_response],
})
Two things this surfaces nicely for your webhook case:
One limit worth stating: this logs the HTTP-level request/response, not the TLS wire bytes. For the actual encrypted stream you need a proxy (mitmproxy, Charles) — httpx can't show you that. |
|
One correction to the hook-based answer above: event hooks can log the HTTPX request/response objects, but they are not an exact wire-byte recorder. I checked this with HTTPX 0.28.1 using a streaming request and a streamed gzip response in
So, for troubleshooting webhook configuration, hooks are useful for method, URL, headers, and application-level bodies if you intentionally buffer them. Redact authorization/cookie values before sharing such logs. If you need the actual HTTP exchange bytes, including content encoding/framing, use an intercepting proxy or a capture at the transport/network layer; HTTPX's event hooks and httpcore logging do not promise a byte-for-byte transcript. AI assistance was used to prepare this reply; I ran the local HTTPX reproduction and checked the official documentation. |
Uh oh!
There was an error while loading. Please reload this page.
Hello there.
I came here through an application that makes use of this library. It is used to call webhooks, and the application allows them to be configured via UI. However, every now and then users have problems getting the configuration right. When troubleshooting it helps a lot if users are able to see both the http request and response - I mean all the bytes or characters that are transmitted.
I checked #3073 but that seems to focus on logging response bodies.
Now the question: How can httpx be used such that all transmitted bytes are getting logged?
All reactions