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.
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_logplus-0.1.0.tar.gz.
File metadata
- Download URL: fastapi_logplus-0.1.0.tar.gz
- Upload date:
- Size: 28.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via:
twine/7.0.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
0685c10801d79b4e68df65d7086874ffde9553c728707402e2feb5df47a4c05d
|
|
| MD5 |
f4e3ba6a139a8f92b9e610931659db42
|
|
| BLAKE2b-256 |
2ce5e6c42e514359a16f6a64c2a462168ba428409b15cf86f1dc7952469d6eec
|
Provenance
The following attestation bundles were made for fastapi_logplus-0.1.0.tar.gz:
Publisher:
publish.yml on Amogha-Hegde/fastapi-logplus
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
fastapi_logplus-0.1.0.tar.gz -
Subject digest:
0685c10801d79b4e68df65d7086874ffde9553c728707402e2feb5df47a4c05d - Sigstore transparency entry: 2292113220
- Sigstore integration time:
-
Permalink:
Amogha-Hegde/fastapi-logplus@74f1d51f972471e92ca855f0b610a4c0a5eba939 -
Branch / Tag:
refs/tags/0.1.0 - Owner: https://github.com/Amogha-Hegde
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@74f1d51f972471e92ca855f0b610a4c0a5eba939 -
Trigger Event:
push
-
Statement type:
File details
Details for the file fastapi_logplus-0.1.0-py3-none-any.whl.
File metadata
- Download URL: fastapi_logplus-0.1.0-py3-none-any.whl
- Upload date:
- Size: 19.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via:
twine/7.0.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f760489325f392af2a79a083b487cca2aa9a69e47325a1452e00387055ee7709
|
|
| MD5 |
2ba227a938f966d1edff183362a2ba09
|
|
| BLAKE2b-256 |
3a73b19a40efaa1f8b270ee2f6359b407dcda386f7818c2e7a20debe9e6928d3
|
Provenance
The following attestation bundles were made for fastapi_logplus-0.1.0-py3-none-any.whl:
Publisher:
publish.yml on Amogha-Hegde/fastapi-logplus
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
fastapi_logplus-0.1.0-py3-none-any.whl -
Subject digest:
f760489325f392af2a79a083b487cca2aa9a69e47325a1452e00387055ee7709 - Sigstore transparency entry: 2292113250
- Sigstore integration time:
-
Permalink:
Amogha-Hegde/fastapi-logplus@74f1d51f972471e92ca855f0b610a4c0a5eba939 -
Branch / Tag:
refs/tags/0.1.0 - Owner: https://github.com/Amogha-Hegde
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@74f1d51f972471e92ca855f0b610a4c0a5eba939 -
Trigger Event:
push
-
Statement type: