FastAPI middleware for request tracing and logging
Project description
FastAPI Trace Middleware
A simple and effective middleware for FastAPI applications that automatically adds trace IDs to requests and integrates with Python logging.
Features
- 🔍 Automatic trace ID generation for each request
- 📝 Seamless integration with Python logging
- 🎛️ Configurable trace ID headers and generators
- 🔄 Context-aware trace ID access throughout your application
- 📦 Easy setup with sensible defaults
Installation
pip install fastapi-trace-middleware
Quick Start
from fastapi import FastAPI
from fastapi_trace import create_trace_middleware, setup_simple_trace_logging
import logging.config
# Setup logging with trace support
logging.config.dictConfig(setup_simple_trace_logging())
app = FastAPI()
# Add trace middleware
trace_middleware = create_trace_middleware()
app.middleware("http")(trace_middleware)
@app.get("/")
async def root():
from fastapi_trace import get_trace_id
logging.info("Processing request") # Will include trace_id automatically
return {"message": "Hello World", "trace_id": get_trace_id()}
Documentation
Basic Usage
The middleware automatically:
- Extracts trace ID from request headers (default:
X-Trace-ID) - Generates a new trace ID if none exists
- Sets the trace ID in context for the entire request lifecycle
- Adds trace ID to response headers
- Makes trace ID available in logs
Configuration
from fastapi_trace import create_trace_middleware
# Custom configuration
trace_middleware = create_trace_middleware(
trace_header="X-Custom-Trace-ID", # Custom header name
include_response_header=True, # Include in response
trace_id_generator=lambda: "custom-" + generate(size=10) # Custom generator
)
Accessing Trace ID
from fastapi_trace import get_trace_id
async def my_function():
trace_id = get_trace_id()
print(f"Current trace ID: {trace_id}")
Integration with Existing Middleware
If you already have context middleware (e.g., for user authentication), you have several options to integrate trace functionality without conflicts:
Option 1: Using Hooks (Recommended)
from fastapi_trace import create_trace_middleware
async def custom_context_hook(request):
# Your existing context setup logic (e.g., Azure user ID)
if auth_header := request.headers.get("Authorization"):
# Extract and set user context
pass
# Create middleware with hooks
trace_middleware = create_trace_middleware(
pre_process_hook=custom_context_hook,
respect_existing_context=True # Don't override existing trace context
)
app.middleware("http")(trace_middleware)
Option 2: Using Utility Functions
from fastapi_trace import setup_trace_context, add_trace_header_to_response
async def enhanced_context_middleware(request, call_next):
# Set up trace context
trace_id = await setup_trace_context(request)
# Your existing context logic
# ... (Azure user ID, etc.)
response = await call_next(request)
# Add trace header
add_trace_header_to_response(response, trace_id)
return response
app.middleware("http")(enhanced_context_middleware)
Option 3: Composable Middleware
from fastapi_trace.integration_examples import create_compatible_middleware
# Your existing middleware function
async def existing_context_middleware(request, call_next):
# Your existing logic
return await call_next(request)
# Create compatible middleware
middleware = create_compatible_middleware(existing_context_middleware)
app.middleware("http")(middleware)
Custom Logging Setup
from fastapi_trace import setup_trace_logging
# Custom formatters and handlers
config = setup_trace_logging(
formatters={
"custom": {
"format": "%(asctime)s [%(trace_id)s] %(levelname)s: %(message)s"
}
}
)
import logging.config
logging.config.dictConfig(config)
Requirements
- Python 3.8+
- FastAPI 0.68.0+
- nanoid 2.0.0+
License
MIT License - see LICENSE file for details.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file fastapi_trace_middleware-1.0.2.tar.gz.
File metadata
- Download URL: fastapi_trace_middleware-1.0.2.tar.gz
- Upload date:
- Size: 10.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.10.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
43672003473df9fac40cbcbb92e417bb3b8e60e0b846b99e7aaaccdd9be6deba
|
|
| MD5 |
506b612fcf22bf6960e95e280f8e570e
|
|
| BLAKE2b-256 |
8b336f192dfd9bf6173f6ca7812707d969931e9a857555b0308d82a66e2935b7
|
File details
Details for the file fastapi_trace_middleware-1.0.2-py3-none-any.whl.
File metadata
- Download URL: fastapi_trace_middleware-1.0.2-py3-none-any.whl
- Upload date:
- Size: 8.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.10.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
91b5a12daf46ad98cf82dec29db5e14f84764cd7902617a03142d160180dfbe9
|
|
| MD5 |
7be27e4713d906c8587b424b75fad631
|
|
| BLAKE2b-256 |
6f63a46d892adf63dbd6687a89f5ee66d857c9b9a85071af9f0e2d48b1163721
|