Skip to main content

fastapi-structured-logging

fastapi-structured-logging is a lightweight Python module that provides structured logging utilities and a configurable FastAPI access logging middleware. It configures structlog for JSON or console output, enriches log events with OpenTelemetry trace and span identifiers, and exposes an AccessLogMiddleware that can record request method, path, query parameters, client IP, user agent, status codes, processing time and more.

The middleware supports filtering, trusted-proxy handling, custom fields and messages, and integrates cleanly with existing Python logging to produce consistent, machine-readable access logs for observability and tracing.

Usage

from fastapi import FastAPI

import fastapi_structured_logging

# Set output to text if stdout is a tty, structured json if not
fastapi_structured_logging.setup_logging()

logger = fastapi_structured_logging.get_logger()

app = FastAPI()

app.add_middleware(fastapi_structured_logging.AccessLogMiddleware)

Important: When using uvicorn.run(), pass log_config=None and access_log=False to prevent uvicorn from re-adding its default plain-text handlers over the structured logging setup. When using the uvicorn CLI, this is not needed — setup_logging() runs during app import, after uvicorn's logging init. Pass --no-access-log to let the middleware handle access logs.

Configuration Options

The library provides extensive configuration options to customize logging and access logging behavior.

setup_logging() Options

  • json_logs (Optional[bool]): Forces JSON output if True, console output if False. Defaults to JSON if stdout is not a tty (e.g., in containers or files). Example: setup_logging(json_logs=True) for always JSON logs.
  • log_level (str): Sets the logging level (e.g., "DEBUG", "INFO", "WARNING"). Defaults to "INFO". Example: setup_logging(log_level="DEBUG") to enable debug logging.

AccessLogMiddleware Options

The middleware can be configured via an AccessLogConfig object passed to the middleware constructor. Example:

from fastapi_structured_logging import AccessLogConfig

config = AccessLogConfig(
    log_level="info",
    include_user_agent=False,
    exclude_paths={"/health"},
    custom_fields={"app_version": "1.0.0"}
)
app.add_middleware(fastapi_structured_logging.AccessLogMiddleware, config=config)

Key options include:

  • enabled (bool): Enables or disables access logging. Default: True.
  • log_level (str): Log level for access logs ("debug", "info", etc.). Default: "info".
  • include_* flags: Control which fields are logged, such as include_method (request method), include_path (request path), include_query_params (query parameters), include_client_ip (client IP), include_user_agent (user agent string), include_forwarded_headers (proxy headers), include_status_code (response status), include_process_time (processing time in ms), include_content_length (response content length), include_referer (referer header). All default to True except include_referer (False).
  • exclude_* sets: Filter out logs for specific paths (exclude_paths), methods (exclude_methods), status codes (exclude_status_codes), or paths only if status is 200 or 404 (exclude_paths_if_ok_or_missing).
  • min_process_time / max_process_time (Optional[float]): Only log requests with processing time within these bounds (in seconds).
  • custom_message (str): Custom log message. Default: "Access".
  • custom_fields (Dict[str, Any]): Additional fields to include in every log entry. Example: {"app_version": "1.0.0"}.
  • logger_name (str): Name of the logger to use. Default: "access_log".
  • trusted_proxy (List[str]): List of CIDR ranges for trusted proxies to extract real client IP. Example: ["10.0.0.0/8", "192.168.0.0/16"].

Convenience functions

  • setup_logging() initialize structlog to use line logging if stdout is a tty or JSONL if not (file, container output etc...)

  • get_logger() return a structlog logger

  • json_serializer() for fast serialization in orjson

    @app.exception_handler(RequestValidationError)
    async def validation_exception_handler(request: Request, exc: RequestValidationError):
        exc_str = f"{exc}".replace("\n", " ").replace("   ", " ")
        logger.error("validation exception", validation_error=json_serializer(exc.errors()))
        content = {"status_code": 10422, "message": exc_str, "data": None}
        return JSONResponse(content=content, status_code=status.HTTP_422_UNPROCESSABLE_ENTITY)
    

Setup dev env

uv venv
uv pip install -r requirements-dev.txt
pre-commit install

Test

. venv/bin/activate
uv pip install -e .[full]
pytest --cov-report html --cov-report term --cov-report xml:cov.xml

Build

echo x.y.z > VERSION
uv pip install -r requirements-release.txt
uv run python -m build -s -w

Metadata

Release files for fastapi-structured-logging 1.0.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fastapi-structured-logging 1.0.3
File Size Uploaded Provenance Actions
fastapi_structured_logging-1.0.3.tar.gz 10.8 kB With provenance Details for fastapi_structured_logging-1.0.3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for fastapi-structured-logging 1.0.3
File Interpreter ABI Platform Actions
fastapi_structured_logging-1.0.3-py3-none-any.whl Python 3 none any Details for fastapi_structured_logging-1.0.3-py3-none-any.whl

Total release size: 21.9 kB

Release files / fastapi_structured_logging-1.0.3.tar.gz

Download URL fastapi_structured_logging-1.0.3.tar.gz
Size 10.8 kB
Tags Source
SHA-256 checksum
How to use checksums
48673ba5671227a71dd1412465b8bf9aeda8ba99399f1c207344a7fe6b87126c
BLAKE2b-256 checksum
How to use checksums
7805dfc87207904851a8cf263f7d9e32295f156288d2f06f7419fd23cb85276e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.12

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Apr 10, 2026.

Transparency log

Release files / fastapi_structured_logging-1.0.3-py3-none-any.whl

Download URL fastapi_structured_logging-1.0.3-py3-none-any.whl
Size 11.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0d19332dac1dabb57adaa2e8d78acb78f9a4b58f6451cee6803344b0284d8462
BLAKE2b-256 checksum
How to use checksums
7a004fdcf96ae659fee7802db64cc0365ab442b1fc426f6c9e029fe8424f0fb2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.12

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Apr 10, 2026.

Transparency log

Security for fastapi-structured-logging 1.0.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for fastapi_structured_logging-1.0.3.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Apr 10, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page