fastapi-logplus
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:
RequestContextMiddlewareRequestLogMiddlewareRequestIdMiddleware
RequestContextMiddleware is the main one to use. It:
- reads incoming context headers like
x-request-idandx-trace-id - generates a request ID when one is missing
- binds request context into log records
- propagates
x-request-idback on the response - can emit request and response logs when enabled through env vars
Public API
Config:
get_logger_configget_logger_config_from_fileget_logger_config_with_fileget_logger_config_without_file
Context helpers:
bind_log_contextbind_request_contextbind_request_idbind_trace_contextget_log_contextget_request_idwrap_with_log_contextwrap_with_request_contextwrap_with_request_idwrap_with_trace_context
Filters and formatters:
RequestIdFilterLogContextFilterSafePlainFormatterSafeColoredFormatterJsonFormatter
INI Config
get_logger_config_from_file() reads a [fastapi-logplus] section. See:
fastapi-logplus.plain.sample.inifastapi-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 exampleINFO,DEBUG,WARNING,ERROR.console_style: console formatter style. Accepted values:plain,color,json.include_request_id: boolean flag that addsRequestIdFilterto handlers and appends request context fields to text logs.include_uvicorn_logs: boolean flag that includes or excludesuvicorn,uvicorn.access, anduvicorn.errorfrom configured named loggers.enable_file_logging: boolean flag that enables timed rotating file logging. If omitted, file logging turns on automatically whenlog_file_nameis 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 asapp.logorapp.json.log. It must be a file name, not a path.file_style: file formatter style. Accepted values:plain,color,json.log_when:TimedRotatingFileHandlerrotation interval. Accepted values:S,M,H,D,MIDNIGHT, orW0throughW6.log_backup: number of rotated files to retain. Must be an integer greater than or equal to0.log_timezone: timezone used by text and JSON formatters. UseUTC,local, or any valid IANA timezone such asAsia/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_REQUESTSFASTAPI_LOGPLUS_LOG_REQUEST_HEADERSFASTAPI_LOGPLUS_LOG_RESPONSE_HEADERSFASTAPI_LOGPLUS_LOG_REQUEST_BODYFASTAPI_LOGPLUS_LOG_RESPONSE_BODYFASTAPI_LOGPLUS_REQUEST_LOGGERFASTAPI_LOGPLUS_BODY_MAX_LENGTHFASTAPI_LOGPLUS_REDACT_HEADERS
Header overrides:
FASTAPI_LOGPLUS_REQUEST_ID_HEADERFASTAPI_LOGPLUS_TRACE_ID_HEADERFASTAPI_LOGPLUS_SPAN_ID_HEADERFASTAPI_LOGPLUS_PROJECT_ID_HEADERFASTAPI_LOGPLUS_ORG_ID_HEADERFASTAPI_LOGPLUS_TENANT_HEADERFASTAPI_LOGPLUS_USER_ID_HEADER
Response propagation flags:
FASTAPI_LOGPLUS_PROPAGATE_TRACE_IDFASTAPI_LOGPLUS_PROPAGATE_SPAN_IDFASTAPI_LOGPLUS_PROPAGATE_PROJECT_IDFASTAPI_LOGPLUS_PROPAGATE_ORG_IDFASTAPI_LOGPLUS_PROPAGATE_TENANTFASTAPI_LOGPLUS_PROPAGATE_USER_ID
Structured output metadata:
FASTAPI_LOGPLUS_SERVICE_NAMEFASTAPI_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)
| 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)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| 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 logRelease 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 logSecurity 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.
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 logA 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.