function logged_request_v1
A wrapper function that intercepts HTTP requests, logs their details (method, URL, headers, body) along with response information, and returns the response object.
/tf/active/vicechatdev/e-ink-llm/cloudtest/raw_request_logger.py
70 - 101
moderate
Purpose
This function serves as a logging middleware for HTTP requests, typically used to monkey-patch or wrap the requests library's request method. It captures request details before sending, executes the actual HTTP request, logs both request and response information using a RawRequestLogger instance, and returns the response. This is useful for debugging, auditing, monitoring API calls, or maintaining request/response history.
Source Code
def logged_request(self, method, url, **kwargs):
"""Wrapper that logs requests before sending"""
global logger
if logger is None:
logger = RawRequestLogger()
# Prepare headers for logging
headers = kwargs.get('headers', {})
# Prepare body for logging
body = None
if 'data' in kwargs:
body = kwargs['data']
if isinstance(body, str):
body = body.encode('utf-8')
elif 'json' in kwargs:
body = json.dumps(kwargs['json']).encode('utf-8')
# Make the actual request
response = original_request(self, method, url, **kwargs)
# Log the request and response
logger.log_request(
method=method.upper(),
url=url,
headers=headers,
body=body,
response_status=response.status_code,
response_text=response.text if len(response.text) < 200 else response.text[:200] + "..."
)
return response
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
self |
- | - | positional_or_keyword |
method |
- | - | positional_or_keyword |
url |
- | - | positional_or_keyword |
**kwargs |
- | - | var_keyword |
Parameter Details
self: The instance object (typically a requests.Session or similar object) that the method is bound to. This allows the function to work as a method replacement for the original request method.
method: HTTP method as a string (e.g., 'GET', 'POST', 'PUT', 'DELETE'). Will be converted to uppercase for logging.
url: The target URL for the HTTP request as a string. Can be a full URL or relative path depending on the session configuration.
**kwargs: Variable keyword arguments passed to the underlying request function. Common kwargs include: 'headers' (dict of HTTP headers), 'data' (request body as string or bytes), 'json' (dict to be JSON-encoded as request body), 'params' (URL query parameters), 'timeout', 'verify', etc. The function specifically extracts 'headers', 'data', and 'json' for logging purposes.
Return Value
Returns a Response object from the requests library containing the HTTP response. The Response object includes attributes like status_code (int), text (str), headers (dict), content (bytes), json() method, etc. The response is returned unchanged after logging.
Dependencies
requestsjson
Required Imports
import requests
import json
Usage Example
import requests
import json
from datetime import datetime
from pathlib import Path
# Define RawRequestLogger class
class RawRequestLogger:
def log_request(self, method, url, headers, body, response_status, response_text):
print(f"{method} {url} - Status: {response_status}")
print(f"Headers: {headers}")
print(f"Body: {body}")
print(f"Response: {response_text}")
# Store original request method
original_request = requests.Session.request
logger = None
# Monkey patch the Session.request method
requests.Session.request = logged_request
# Use requests as normal - all requests will be logged
session = requests.Session()
response = session.get('https://api.example.com/data')
print(response.status_code)
# POST with JSON body
response = session.post('https://api.example.com/users', json={'name': 'John', 'age': 30})
print(response.json())
Best Practices
- Ensure 'original_request' is properly saved before monkey-patching to avoid infinite recursion
- The global 'logger' variable should be thread-safe if used in multi-threaded environments
- Response text is truncated to 200 characters for logging to prevent excessive log sizes - adjust this limit based on your needs
- Consider adding error handling around the logging operations to prevent logging failures from breaking actual requests
- Be cautious about logging sensitive data in headers or body (e.g., API keys, passwords) - consider sanitizing before logging
- The function assumes 'RawRequestLogger' has a 'log_request' method with the specific signature shown
- Body encoding assumes UTF-8 - may need adjustment for other encodings
- This pattern modifies global state (monkey-patching) which can make testing and debugging more difficult
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function logged_request_v2 89.1% similar
-
function logged_request 74.0% similar
-
class RawRequestLogger 67.7% similar
-
function log_controller_action_v1 51.7% similar
-
function log_controller_action 49.7% similar