Search code examples
pythonhttpx

Python httpx log all request headers


How can I log all request headers of an httpx request? I use log level DEBUG nad response headers log fine but there are no request headers in the log. If it matters I'm using async api of httpx lib.


Solution

  • Use custom event hooks:

    import httpx
    import logging
    
    logging.basicConfig(level=logging.DEBUG)
    async def log_request(request):
        logging.debug(f"Request headers: {request.headers}")
    async with httpx.AsyncClient(event_hooks={'request': [log_request]}) as client:
        response = await client.get('https://httpbin.org/get')