Skip to main content

fastapi-logplus

Tests Coverage PyPI version Python versions PyPI downloads

fastapi-logplus is a reusable logging toolkit for FastAPI services. It gives you one place to standardize logging config, request-scoped context, structured output, and uvicorn logger behavior across services.

Features

  • plain, color, or JSON log output
  • optional timed rotating file logging
  • request-scoped context via ContextVar
  • request ID generation and propagation
  • trace, span, project, org, tenant, and user context extraction
  • request and response summary/header/body logging
  • per-logger level overrides for uvicorn, fastapi, starlette, and app loggers

Installation

Base install:

pip install fastapi-logplus

With colored console logging:

pip install "fastapi-logplus[color]"

With JSON logging support:

pip install "fastapi-logplus[json]"

For development and tests:

pip install "fastapi-logplus[test]"

Quick Start

import logging.config

from fastapi import FastAPI

from fastapi_logplus import RequestContextMiddleware, get_logger_config

app = FastAPI()
app.add_middleware(RequestContextMiddleware)

logging.config.dictConfig(
    get_logger_config(
        log_level="INFO",
        console_style="color",
        include_request_id=True,
    )
)


@app.get("/health")
async def health():
    return {"ok": True}

Runnable example:

python -m examples.basic_app

JSON Logging Example

import logging.config

from fastapi_logplus import get_logger_config

logging.config.dictConfig(
    get_logger_config(
        log_level="INFO",
        console_style="json",
        include_request_id=True,
        logger_levels={
            "uvicorn.access": "WARNING",
        },
    )
)

File Logging Example

import logging.config
from pathlib import Path

from fastapi_logplus import get_logger_config

logging.config.dictConfig(
    get_logger_config(
        log_level="INFO",
        base_dir=Path("."),
        log_file_name="app.log",
        enable_file_logging=True,
        console_style="plain",
        file_style="json",
        include_request_id=True,
    )
)

This creates ./logs/app.log with timed rotation via TimedRotatingFileHandler.

Middleware

Available middleware exports:

  • RequestContextMiddleware
  • RequestLogMiddleware
  • RequestIdMiddleware

RequestContextMiddleware is the main one to use. It:

  • reads incoming context headers like x-request-id and x-trace-id
  • generates a request ID when one is missing
  • binds request context into log records
  • propagates x-request-id back on the response
  • can emit request and response logs when enabled through env vars

Public API

Config:

  • get_logger_config
  • get_logger_config_from_file
  • get_logger_config_with_file
  • get_logger_config_without_file

Context helpers:

  • bind_log_context
  • bind_request_context
  • bind_request_id
  • bind_trace_context
  • get_log_context
  • get_request_id
  • wrap_with_log_context
  • wrap_with_request_context
  • wrap_with_request_id
  • wrap_with_trace_context

Filters and formatters:

  • RequestIdFilter
  • LogContextFilter
  • SafePlainFormatter
  • SafeColoredFormatter
  • JsonFormatter

INI Config

get_logger_config_from_file() reads a [fastapi-logplus] section. See:

  • fastapi-logplus.plain.sample.ini
  • fastapi-logplus.json.sample.ini

Minimal example:

[fastapi-logplus]
log_level = INFO
console_style = color
include_request_id = true
include_uvicorn_logs = true

Full plain-text sample:

[fastapi-logplus]
log_level = INFO
console_style = plain
include_request_id = true
include_uvicorn_logs = true
enable_file_logging = true
base_dir = .
log_file_name = app.log
file_style = plain
log_when = W0
log_backup = 100
log_timezone = UTC
app_loggers =
    main

[logger_levels]
uvicorn.access = WARNING
uvicorn.error = INFO
fastapi = INFO
main = DEBUG

[text_field_defaults]
tenant = -
user_id = null

Full JSON sample:

[fastapi-logplus]
log_level = INFO
console_style = json
include_request_id = true
include_uvicorn_logs = true
enable_file_logging = true
base_dir = .
log_file_name = app.json.log
file_style = json
log_when = W0
log_backup = 100
log_timezone = UTC
app_loggers =
    main

[logger_levels]
uvicorn.access = WARNING
uvicorn.error = INFO
main = DEBUG

[json_fields]
timestamp = timestamp
level = levelname
logger = name
message = message
event = event
method = method
path = path
status_code = status_code
request_id = request_id
trace_id = trace_id
tenant = tenant
user_id = user_id
duration_ms = duration_ms

[json_field_defaults]
tenant = -
user_id = null

[text_field_defaults]
tenant = -
user_id = null

[fastapi-logplus]

  • log_level: required default log level for configured app loggers. Values are normalized to uppercase, for example INFO, DEBUG, WARNING, ERROR.
  • console_style: console formatter style. Accepted values: plain, color, json.
  • include_request_id: boolean flag that adds RequestIdFilter to handlers and appends request context fields to text logs.
  • include_uvicorn_logs: boolean flag that includes or excludes uvicorn, uvicorn.access, and uvicorn.error from configured named loggers.
  • enable_file_logging: boolean flag that enables timed rotating file logging. If omitted, file logging turns on automatically when log_file_name is set.
  • base_dir: base path used for file logging. Log files are written under <base_dir>/logs/.
  • log_file_name: file name for rotating file logs, such as app.log or app.json.log. It must be a file name, not a path.
  • file_style: file formatter style. Accepted values: plain, color, json.
  • log_when: TimedRotatingFileHandler rotation interval. Accepted values: S, M, H, D, MIDNIGHT, or W0 through W6.
  • log_backup: number of rotated files to retain. Must be an integer greater than or equal to 0.
  • log_timezone: timezone used by text and JSON formatters. Use UTC, local, or any valid IANA timezone such as Asia/Kolkata.
  • app_loggers: comma-separated or multiline list of additional named loggers to configure.

Boolean INI values accept 1, true, yes, on, 0, false, no, and off.

[logger_levels]

Use this section for per-logger level overrides:

[logger_levels]
uvicorn.access = WARNING
uvicorn.error = INFO
fastapi = INFO
main = DEBUG

Each key is a logger name and each value is a log level. Logger names listed here are also added to the configured logger set.

[json_fields]

Use this section only with JSON output. Each key is the output JSON key and each value is the source LogRecord field:

[json_fields]
timestamp = timestamp
level = levelname
logger = name
message = message
event = event
method = method
path = path
status_code = status_code
request_id = request_id
trace_id = trace_id
tenant = tenant
user_id = user_id
duration_ms = duration_ms

Special source fields include timestamp, asctime, message, and hostname. Other values are read directly from the log record, including request context fields populated by middleware and filters.

[json_field_defaults]

Use this section to provide fallback JSON values when a mapped field is missing:

[json_field_defaults]
tenant = -
user_id = null

The literal INI value null becomes Python None; fields with None values are omitted from JSON output.

[text_field_defaults]

Use this section to provide fallback values for text formatter fields:

[text_field_defaults]
tenant = -
user_id = null

These defaults prevent text format strings from failing when optional request context fields are absent.

[log_colors]

Optional color formatter overrides can be supplied as level-to-color mappings:

[log_colors]
DEBUG = blue
INFO = bold_white
WARNING = yellow
ERROR = red
CRITICAL = bold_red

This section is used by console_style = color or file_style = color and requires the color extra for colored output.

Environment Variables

See .env.example for copyable example values.

Request logging configuration:

  • FASTAPI_LOGPLUS_LOG_REQUESTS
  • FASTAPI_LOGPLUS_LOG_REQUEST_HEADERS
  • FASTAPI_LOGPLUS_LOG_RESPONSE_HEADERS
  • FASTAPI_LOGPLUS_LOG_REQUEST_BODY
  • FASTAPI_LOGPLUS_LOG_RESPONSE_BODY
  • FASTAPI_LOGPLUS_REQUEST_LOGGER
  • FASTAPI_LOGPLUS_BODY_MAX_LENGTH
  • FASTAPI_LOGPLUS_REDACT_HEADERS

Header overrides:

  • FASTAPI_LOGPLUS_REQUEST_ID_HEADER
  • FASTAPI_LOGPLUS_TRACE_ID_HEADER
  • FASTAPI_LOGPLUS_SPAN_ID_HEADER
  • FASTAPI_LOGPLUS_PROJECT_ID_HEADER
  • FASTAPI_LOGPLUS_ORG_ID_HEADER
  • FASTAPI_LOGPLUS_TENANT_HEADER
  • FASTAPI_LOGPLUS_USER_ID_HEADER

Response propagation flags:

  • FASTAPI_LOGPLUS_PROPAGATE_TRACE_ID
  • FASTAPI_LOGPLUS_PROPAGATE_SPAN_ID
  • FASTAPI_LOGPLUS_PROPAGATE_PROJECT_ID
  • FASTAPI_LOGPLUS_PROPAGATE_ORG_ID
  • FASTAPI_LOGPLUS_PROPAGATE_TENANT
  • FASTAPI_LOGPLUS_PROPAGATE_USER_ID

Structured output metadata:

  • FASTAPI_LOGPLUS_SERVICE_NAME
  • FASTAPI_LOGPLUS_ENVIRONMENT

Scope

This package focuses on application logging and request context for FastAPI services. It does not try to replace full observability tooling.

Metadata

Release files for fastapi-logplus 0.1.0

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-logplus 0.1.0
File Size Uploaded Provenance Actions
fastapi_logplus-0.1.0.tar.gz 28.7 kB With provenance Details for fastapi_logplus-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for fastapi-logplus 0.1.0
File Interpreter ABI Platform Actions
fastapi_logplus-0.1.0-py3-none-any.whl Python 3 none any Details for fastapi_logplus-0.1.0-py3-none-any.whl

Total release size: 48.1 kB

Release files / fastapi_logplus-0.1.0.tar.gz

Download URL fastapi_logplus-0.1.0.tar.gz
Size 28.7 kB
Tags Source
SHA-256 checksum
How to use checksums
0685c10801d79b4e68df65d7086874ffde9553c728707402e2feb5df47a4c05d
BLAKE2b-256 checksum
How to use checksums
2ce5e6c42e514359a16f6a64c2a462168ba428409b15cf86f1dc7952469d6eec
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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 Jul 30, 2026.

Transparency log

Release files / fastapi_logplus-0.1.0-py3-none-any.whl

Download URL fastapi_logplus-0.1.0-py3-none-any.whl
Size 19.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f760489325f392af2a79a083b487cca2aa9a69e47325a1452e00387055ee7709
BLAKE2b-256 checksum
How to use checksums
3a73b19a40efaa1f8b270ee2f6359b407dcda386f7818c2e7a20debe9e6928d3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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 Jul 30, 2026.

Transparency log

Security for fastapi-logplus 0.1.0

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_logplus-0.1.0.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 Jul 30, 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.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files Full provenance

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