1 min read

Python Structlog Module

structlog makes logging in Python less painful and more powerful by adding structure to your log entries. It encourages logging key-value pairs rather than unstructured strings, making logs machine-readable and easier to query.

Installation

pip install structlog

Basic Usage

You can use structlog.get_logger() to get a logger.

import structlog

log = structlog.get_logger()

log.info("greeted", whom="world", more_than_strings=True)
# Output (default): 2023-01-01 12:00.00 greeted                        more_than_strings=True whom='world'

Binding Context

You can create a new logger with context values bound to it. This is useful for request IDs or user IDs.

log = structlog.get_logger()
log = log.bind(user="anonymous", email="user@example.com")

log.info("user_logged_in", happy=True)
# Output includes user='anonymous' email='user@example.com' happy=True

Configuration

structlog is highly configurable. You can define a chain of processors to modify the log event before it is rendered.

import structlog

structlog.configure(
    processors=[
        structlog.processors.TimeStamper(fmt="iso"),
        structlog.processors.JSONRenderer()
    ]
)

log = structlog.get_logger()
log.info("event_started")
# Output: {"event": "event_started", "timestamp": "2023-10-27T10:00:00Z"}

Integration with Standard Logging

structlog can wrap the standard library's logging module to add structure while keeping existing configuration.

programming/python/python