Skip to content

Easy mechanism for logging response bodies using event hooks? #3073

Answered by karpetrosyan
simonw asked this question in General
Discussion options

You must be logged in to vote

Hi!

You can try something like this:

import httpx


class LogResponse(httpx.Response):
    def iter_bytes(self, *args, **kwargs):
        for chunk in super().iter_bytes(*args, **kwargs):
            print(chunk)
            yield chunk


class LogTransport(httpx.BaseTransport):
    def __init__(self, transport: httpx.BaseTransport):
        self.transport = transport

    def handle_request(self, request: httpx.Request) -> httpx.Response:
        response = self.transport.handle_request(request)

        return LogResponse(
            status_code=response.status_code,
            headers=response.headers,
            stream=response.stream,
            extensions=response.extensions,
  …

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@simonw
Comment options

@dude-abides
Comment options

@haoyun
Comment options

Answer selected by simonw
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
4 participants