Structured JSON logging with automatic context propagation.
pip install philiprehberger-struct-logStructured JSON logging with automatic context propagation.
pip install philiprehberger-struct-log
from philiprehberger_struct_log import get_logger
logger = get_logger("myapp")
logger.info("Server started", extra={"port": 8080})
# {"timestamp": "2026-03-21T12:00:00+00:00", "level": "INFO", "message": "Server started", "logger": "myapp", "port": 8080}
from philiprehberger_struct_log import get_logger, bind_context, clear_context
logger = get_logger("myapp")
bind_context(request_id="abc-123", user="alice")
logger.info("Processing request")
# {"timestamp": "...", "level": "INFO", "message": "Processing request", "logger": "myapp", "request_id": "abc-123", "user": "alice"}
clear_context()
Use log_context as a context manager for nested scoped context. On exit, the previous context is automatically restored.
from philiprehberger_struct_log import get_logger, log_context
logger = get_logger("myapp")
with log_context(request_id="abc"):
logger.info("handling") # includes request_id
with log_context(user_id="123"):
logger.info("auth") # includes request_id AND user_id
logger.info("done") # only request_id
from philiprehberger_struct_log import bind_context, get_context
bind_context(service="api", env="production")
ctx = get_context()
# {"service": "api", "env": "production"}
| Name | Description |
|---|---|
get_logger(name) | Get or create a logger with a StructHandler attached. Level is set to DEBUG. |
bind_context(**kwargs) | Store key-value pairs in thread-local context. Included in every log entry on the current thread. |
clear_context() | Clear all bound context for the current thread. |
get_context() | Return a copy of the current thread-local context as a dict. |
log_context(**kwargs) | Context manager that merges kwargs into context on enter and restores previous context on exit. Supports nesting. |
StructHandler(stream=None) | Logging handler that formats records as JSON lines. Defaults to stderr. |
| Field | Description |
|---|---|
timestamp | ISO 8601 UTC timestamp |
level | Log level name (DEBUG, INFO, WARNING, ERROR, CRITICAL) |
message | Formatted log message |
logger | Logger name |
Bound context fields and any extra={} kwargs passed to the log call are merged into the top-level JSON object.
pip install -e .
python -m pytest tests/ -v
If you find this project useful: