Skip to main content

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:

  1. Extracts trace ID from request headers (default: X-Trace-ID)
  2. Generates a new trace ID if none exists
  3. Sets the trace ID in context for the entire request lifecycle
  4. Adds trace ID to response headers
  5. 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}")

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

fastapi_trace_middleware-1.0.0.tar.gz (5.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastapi_trace_middleware-1.0.0-py3-none-any.whl (6.2 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_trace_middleware-1.0.0.tar.gz.

File metadata

File hashes

Hashes for fastapi_trace_middleware-1.0.0.tar.gz
Algorithm Hash digest
SHA256 5e993c3532c71d992d1f5f8f8b305fe4b127d28629866b8790bde926446f055f
MD5 ee38f319f8ecceaff12bc21a5c28b76b
BLAKE2b-256 5f6440a33da9309d199fb97f2b513e721357179804cfec3aadf7a84f15c1e019

See more details on using hashes here.

File details

Details for the file fastapi_trace_middleware-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_trace_middleware-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 01a71f38a6c6f92d2bf951754d2f1440751e30487f8426ab2c13bad834e5601c
MD5 13d793ad7758a33c2ad87e32cf72fffb
BLAKE2b-256 a32f65a4f69acd718fb5a540de18816a6f33fa301e96285d95f680dd559b278a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page