Some text some message..
Back 🌟 What is structlog : structured logging library 18 Aug, 2025

🌟 What is structlog?

  • structlog is a structured logging library for Python.

  • Unlike the standard logging module that mainly produces plain text, structlog produces structured logs, usually as dictionaries, JSON, or any format you define.

  • Ideal for modern applications, especially when logs are sent to log aggregators (like ELK stack, Splunk, Datadog).


🔹 Installation

pip install structlog

🔹 Basic Example

import structlog

# Configure structlog
structlog.configure(
    processors=[
        structlog.processors.KeyValueRenderer()  # Makes logs key=value style
    ]
)

# Get a logger
log = structlog.get_logger()

# Log messages
log.info("user_logged_in", user="Abhishek", method="password")
log.warning("low_balance", user="Abhishek", balance=50)

Output Example:

event='user_logged_in' user='Abhishek' method='password'
event='low_balance' user='Abhishek' balance=50

🔹 Features of structlog

Feature Description
Structured Logs as dictionaries/JSON instead of plain text
Flexible Use different renderers (JSON, key=value, custom)
Processor chain Pre-process logs before rendering (add timestamps, filters, etc.)
Compatible Works with Python's standard logging module

🔹 Advanced Example with Standard Logging

import logging
import structlog

# Standard logging config
logging.basicConfig(level=logging.INFO, format="%(message)s")

# Configure structlog
structlog.configure(
    processors=[
        structlog.stdlib.add_log_level,
        structlog.stdlib.add_logger_name,
        structlog.processors.TimeStamper(fmt="iso"),
        structlog.stdlib.ProcessorFormatter.wrap_for_formatter,
    ],
    logger_factory=structlog.stdlib.LoggerFactory(),
)

# Get logger
log = structlog.get_logger("my_struct_logger")

log.info("payment_successful", user="Abhishek", amount=500)
log.error("payment_failed", user="Abhishek", amount=1000)

Output Example:

timestamp='2025-08-18T10:45:00Z' level='info' logger='my_struct_logger' event='payment_successful' user='Abhishek' amount=500
timestamp='2025-08-18T10:45:01Z' level='error' logger='my_struct_logger' event='payment_failed' user='Abhishek' amount=1000

✅ Why Use structlog?

  • Perfect for microservices or cloud apps.

  • Makes logs machine-readable (for analytics, monitoring, and alerting).

  • Can co-exist with standard logging.

  • Easy to add extra context (user, request ID, session info).