Context-enriched logging mixin with optional auto-instrumentation
Project description
csrd.logging
Context-enriched logging for all application layers.
Dependency tier
Tier 1 csrd.models · csrd.lifespan · csrd.context
Tier 1.5 csrd.logging ← depends on csrd.context only
Tier 2 csrd.delegate · csrd.repository · csrd.service
Tier 3 csrd.versioning
Components
ContextLogger
A stdlib Logger wrapper that auto-enriches every message with request context (hit_id, user_id, path params) as key=value pairs.
from csrd.logging import ContextLogger
logger = ContextLogger(logging.getLogger(__name__))
logger.info("Order created", meta={"order_id": 42})
# → "Order created hit_id=abc-123 user_id=user1 order_id=42"
All standard logging kwargs (exc_info, extra, stacklevel) pass through. The meta kwarg adds extra key=value pairs per call.
LoggingMixin
A mixin providing self.log (a ContextLogger) for any class. Works at every layer.
from csrd.logging import LoggingMixin
class OrderService(BaseService, LoggingMixin):
async def place_order(self, cart):
self.log.info("Placing order", meta={"items": len(cart)})
Auto-logging (opt-in)
Pass auto_log=True to automatically log entry and exceptions for every public method:
class OrderService(BaseService, LoggingMixin, auto_log=True):
async def place_order(self, cart): # ← entry logged at INFO, exceptions at ERROR
...
Exclude noisy methods:
class MyService(BaseService, LoggingMixin, auto_log=True):
__log_exclude__ = {"health_check"}
Both sync and async methods are handled. Private methods (_name) are always skipped.
RequestContextFilter
A stdlib logging.Filter that injects context fields into log records (not messages). Use this when your logging backend (Splunk, ELK, Datadog) needs structured fields in a configurable format.
Fields added to each record:
| Field | Source | Default |
|---|---|---|
hit_id |
Request trace ID | "-" |
user_id |
Authenticated user's sub claim |
"-" |
app_id |
Application identifier header | "-" |
api_version |
Resolved API version | "-" |
Production logging configuration
ContextLogger enriches log messages — it works out of the box with zero configuration. For production deployments you'll typically also want to configure stdlib logging with structured formatters, handlers, and filters.
Approach 1: ContextLogger only (simplest)
No configuration needed. Messages include context automatically:
2025-07-15 10:23:45 INFO Order created hit_id=abc-123 user_id=user1 order_id=42
Good for development and simple deployments.
Approach 2: YAML logging configuration (production)
Create a config/logging.yml in your application:
version: 1
disable_existing_loggers: false
formatters:
structured:
style: "{"
format: "{asctime} hitId={hit_id} userId={user_id} module={name} func={funcName} level={levelname} {message}"
filters:
context:
"()": csrd.logging.RequestContextFilter
handlers:
console:
class: logging.StreamHandler
level: INFO
formatter: structured
stream: ext://sys.stdout
filters: [context]
loggers:
uvicorn:
handlers: [console]
level: INFO
propagate: false
uvicorn.access:
handlers: [console]
level: INFO
propagate: false
root:
level: INFO
handlers: [console]
Load it at startup:
import logging.config
import yaml
from pathlib import Path
with open(Path("config/logging.yml")) as f:
logging.config.dictConfig(yaml.safe_load(f))
Approach 3: Both together (recommended for production)
Use ContextLogger / LoggingMixin in your code for dev-friendly messages, and attach RequestContextFilter to your production handlers for structured logging backends. The two are complementary — ContextLogger enriches the message text, RequestContextFilter adds record-level fields for formatters.
When to use which
| Approach | Context in logs | Config required | Best for |
|---|---|---|---|
ContextLogger |
In message text (key=value) |
None | Dev, simple apps |
logging.yml + RequestContextFilter |
In log record fields | YAML file | Splunk, ELK, structured logging |
| Both together | Both | YAML file | Full production setup |
Installation
uv add csrd-logging
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 csrd_logging-0.3.12.tar.gz.
File metadata
- Download URL: csrd_logging-0.3.12.tar.gz
- Upload date:
- Size: 8.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d2eda0bdf8021dc24e562b010ed3e863a32bda90e679218bb2b6888e04a37461
|
|
| MD5 |
c264deb9c16380f8af014129743e6a91
|
|
| BLAKE2b-256 |
8186543efe7fa997d69c4b068b9a58666260d13de5bdd467769fd573f3992913
|
Provenance
The following attestation bundles were made for csrd_logging-0.3.12.tar.gz:
Publisher:
release.yml on csrd-api/fastapi-common
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
csrd_logging-0.3.12.tar.gz -
Subject digest:
d2eda0bdf8021dc24e562b010ed3e863a32bda90e679218bb2b6888e04a37461 - Sigstore transparency entry: 1421809393
- Sigstore integration time:
-
Permalink:
csrd-api/fastapi-common@368b9bed4e3681b8dacf7140c18054446c806cee -
Branch / Tag:
refs/tags/v0.3.12 - Owner: https://github.com/csrd-api
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@368b9bed4e3681b8dacf7140c18054446c806cee -
Trigger Event:
workflow_dispatch
-
Statement type:
File details
Details for the file csrd_logging-0.3.12-py3-none-any.whl.
File metadata
- Download URL: csrd_logging-0.3.12-py3-none-any.whl
- Upload date:
- Size: 6.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
665305097141dd0a77582a6d8b738112a6c68578c46ffa69a31f15e032b1c7a1
|
|
| MD5 |
2f038be690685d304e613764b418ad48
|
|
| BLAKE2b-256 |
136f88c02b1f9d2c177f8eff98916fee4398aaff99a4a18bd95603d01737fd7a
|
Provenance
The following attestation bundles were made for csrd_logging-0.3.12-py3-none-any.whl:
Publisher:
release.yml on csrd-api/fastapi-common
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
csrd_logging-0.3.12-py3-none-any.whl -
Subject digest:
665305097141dd0a77582a6d8b738112a6c68578c46ffa69a31f15e032b1c7a1 - Sigstore transparency entry: 1421810513
- Sigstore integration time:
-
Permalink:
csrd-api/fastapi-common@368b9bed4e3681b8dacf7140c18054446c806cee -
Branch / Tag:
refs/tags/v0.3.12 - Owner: https://github.com/csrd-api
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@368b9bed4e3681b8dacf7140c18054446c806cee -
Trigger Event:
workflow_dispatch
-
Statement type: