structlog
Structured logging library for Python that renders key-value events as JSON or pretty console output.
Official Documentation ↗v24. Check the official docs for the latest API surface.Installation
pip install structlogMethods
No methods match this filter.
Structured logging library for Python that renders key-value events as JSON or pretty console output.
Overview
structlog makes logs events rather than formatted strings. Loggers accept an event name plus keyword context, and a configurable processor chain adds timestamps, log levels, bound and contextvar-scoped values, then renders JSON or a colored development view.
It integrates with stdlib logging instead of fighting it, so existing handlers, levels, and third-party libraries can share the same output pipeline. Context binding, per request or per module, turns scattered log lines into correlated traces without passing a logger everywhere.
Core Methods
The most frequently used entry points, with signatures and runnable examples:
structlog.configure— Sets the processor pipeline every logger runs: context injection, timestamping, and final rendering.structlog.get_logger— Returns a logger whose calls take an event name plus arbitrary keyword context rendered as JSON keys.bind_contextvars— Binds context that every subsequent log event in this async context carries automatically.stdlib integration— Routes structlog and stdlib logging records through one shared pipeline for uniform JSON output.
Usage Notes
- Order matters in processors: merging context must precede rendering; timestamps usually follow.
- Adopt one event vocabulary early, order.shipped not shipped the order, so dashboards stay consistent.
- Use ConsoleRenderer in development and JSONRenderer in production, selected by environment.
Common Pitfalls
- Forgetting merge_contextvars silently drops all request context from output.
- Passing non-serializable objects as values breaks JSON rendering; pre-format them to strings.
- Binding context without clearing between requests leaks one request fields into the next.
FAQ
- Why key-value events instead of printf-style messages?
- Structured events are queryable: filter by order_id in your log platform instead of grepping formatted strings. Rendering decisions, JSON for machines or pretty colors for consoles, become a config choice instead of call-site code.
- How is context attached to every log line?
- Use bind_contextvars for per-request or per-task context in async code, and log.bind(service="billing") for object or module scope. merge_contextvars must be first in the processor chain for the values to appear.
- Can structlog replace the stdlib logging module?
- It wraps rather than replaces: stdlib remains the routing and handler layer, while structlog supplies structure and ergonomics. ProcessorFormatter bridges both so third-party stdlib logs share your JSON format.
Report a problem with this API docOpens a pre-filled issue on GitHub.