API Navigator Logo

Python Requests Logging Example

Author: Newtum

This example shows how to enable detailed logging for the Python Requests library to debug HTTP requests and responses.

Enabling Debug Logging

You can enable debug logging for the underlying `urllib3` library by setting the log level of `http.client` to `DEBUG`. This will print detailed information about the request, headers, and response to the console.

import requests
import logging
import http.client

# Enable debugging at http.client level (requests->urllib3->http.client)
http.client.HTTPConnection.debuglevel = 1

logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True

print("--- Making a request with logging enabled ---")
# The logs will appear in the console where this script is run, not here.
# In this environment, we can't capture the low-level log output.
# The code below is how you would trigger it.
# response = requests.get('https://httpbin.org/get')

print("Status Code: 200 (simulated)")
print("\nLogging has been configured. In a real environment, you would see detailed request/response logs in your console.")