Structured logging utilities for FastAPI and Celery powered by structlog.
Project description
fastapi-celery-structlog
Structured logging helpers for FastAPI and Celery using structlog.
Features
- One-line logging setup for app and workers
- JSON logs in non-dev envs, readable console logs in dev
- Timed rotating file logs (
logs/app.json.log) - FastAPI request/response middleware with:
- request id + correlation id propagation
- response timing
- optional response body capture for selected status codes
- response body sanitization and size limits
- Celery task context binding via signals:
- task id
- task name
- task args/kwargs
- Dynamic runtime resolution for:
env_valuebase_dir
Installation
pip install fastapi-celery-structlog
Or with uv in this repo:
uv sync
Quick Start (FastAPI)
from fastapi import FastAPI
from fastapi_celery_structlog import configure_logging
from fastapi_celery_structlog.middlewares import (
RequestIDMiddleware,
StructlogRequestMiddleware,
)
configure_logging()
app = FastAPI()
app.add_middleware(StructlogRequestMiddleware, project_name="my-service")
app.add_middleware(RequestIDMiddleware)
Middleware order is intentional. FastAPI/Starlette executes middleware in reverse registration order on incoming requests, so RequestIDMiddleware must be registered after StructlogRequestMiddleware to run first at request time (and after it on response).
If you reverse the registration order, StructlogRequestMiddleware builds its request log context before RequestIDMiddleware has populated scope["state"]["request_id"]/scope["state"]["correlation_id"], so request IDs will be missing in logs.
Quick Start (Celery)
from celery import Celery
from fastapi_celery_structlog.celery import configure_celery_logging
celery_app = Celery("my-worker")
configure_celery_logging(celery_app=celery_app)
This configures logging and binds task context using task_prerun/task_postrun.
Example Project
A runnable FastAPI + Celery demo is included at:
examples/fastapi_celery_demo
See:
examples/fastapi_celery_demo/README.md
Dynamic env_value and base_dir
Both configure_logging(...) and configure_celery_logging(...) accept optional:
env_valuebase_dir
If omitted, values are resolved dynamically.
env_value resolution order
- Explicit argument (
env_value=...) - Environment variables (first match):
ENVAPP_ENVFASTAPI_ENVENVIRONMENT
- Fallback:
"development"
base_dir resolution order
- Explicit argument (
base_dir=...) - Environment variables (first match):
FASTAPI_CELERY_STRUCTLOG_BASE_DIRBASE_DIRAPP_BASE_DIR
- Project root auto-detection by walking up from current path and finding:
pyproject.tomlor.git
- Fallback: current working directory
Examples
# Fully dynamic
configure_logging()
# Explicit override
configure_logging(base_dir="/srv/my-service", env_value="production")
configure_celery_logging(
celery_app=celery_app,
base_dir="/srv/my-service",
env_value="production",
worker_hijack_root_logger=False,
)
API
configure_logging(base_dir=None, env_value=None) -> None
Configures Python logging + structlog processors for the application.
configure_celery_logging(celery_app=None, base_dir=None, env_value=None, worker_hijack_root_logger=False) -> None
Configures logging for Celery workers and wires Celery signal handlers for task context binding.
Middlewares
RequestIDMiddleware
- Reads incoming
x-request-id/request-id - Reads incoming
x-correlation-id/correlation-id - Generates missing IDs
- Adds both IDs to response headers
StructlogRequestMiddleware
Logs structured request/response events with environment, user, service, request, response, system, and duration fields.
Key options:
project_nameip_logging_enabledlog_4xx_levelmax_body_bytescapture_body_statusescapture_only_jsoninclude_endpoint_sourcecancelled_status_codecancelled_is_error
Log Output Behavior
- Development-like envs (
dev,local,development):- console renderer for readability
- Other envs:
- JSON renderer
- Always writes rotating JSON logs to:
logs/app.json.log
Celery Notes
- Task context vars are bound in
task_prerunand cleared intask_postrun. - If you pass a
celery_app,worker_hijack_root_loggeris set oncelery_app.conf.
Running Tests
.venv/bin/python -m unittest discover -s tests -v
Project Structure
fastapi_celery_structlog/
__init__.py
runtime.py
settings.py
utils.py
celery/
__init__.py
logger.py
middlewares/
__init__.py
request_id.py
request_response.py
examples/
fastapi_celery_demo/
api.py
celery_app.py
tasks.py
Project details
Release history Release notifications | RSS feed
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_celery_structlog-0.1.1.tar.gz.
File metadata
- Download URL: fastapi_celery_structlog-0.1.1.tar.gz
- Upload date:
- Size: 70.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
52a9a7596c73735cef84a5fa1ca9554b4288216f65087e0ce31cff407b703af4
|
|
| MD5 |
239415ce7986602fd8c5ddd65c5fe14f
|
|
| BLAKE2b-256 |
9c20a15f485d08e83f0e49d85b0ef857315a47de70e6c441351ca504bdad0fd2
|
File details
Details for the file fastapi_celery_structlog-0.1.1-py3-none-any.whl.
File metadata
- Download URL: fastapi_celery_structlog-0.1.1-py3-none-any.whl
- Upload date:
- Size: 24.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
6ae6169b1a7aea8103ba18e173f488d0e2a8cea8753b5c65d300e57f5a9d59f3
|
|
| MD5 |
6e57ab9bf0e7a47b29eb79c4cdc723c7
|
|
| BLAKE2b-256 |
7e653bac6bfe0f8da6d854b1bd5eebf4cf7426be4aa0b7367a423a77a6911947
|