structlog

Structured, typed logging for Python built on plain functions and dictionaries instead of a bespoke logging DSL.

Library
PyPI
v26.1.0
4,982 stars
MIT OR Apache-2.0

Repository Health

Pre-computed score based on development activity, maintenance, community, maturity, and trend momentum. How we score it →
77 /100 Good
Development Activity 84
Maintenance 60
Community 64
Maturity 60
Momentum 40

Technical Analysis

AI-assessed by reading the actual repository — architecture, code quality, innovation, and documentation. How we score it →
86 /100 Excellent
Architecture 90
Code Quality 95
Innovation 80
Learning Curve 80

structlog replaces Python’s ad-hoc string-formatted log lines with structured events: every log call produces a dictionary of key-value pairs that flows through a pipeline of composable processors before being rendered. Instead of parsing free-text messages downstream, consumers get JSON, logfmt, or colorized console output straight from the same event data, with the pipeline fully configurable per application.

The library has been in production use since 2013 and has grown alongside the Python ecosystem, adding first-class support for asyncio, contextvars-based context binding, and full type hints along the way. It can run standalone (rendering its own output) or forward everything into the standard library’s logging module, so teams can adopt it incrementally without ripping out existing log handlers.

Because processors are just callables that take and return an event dict, extending or customizing the pipeline (adding timestamps, stack traces, request IDs, or custom renderers) is a matter of writing or reordering plain functions rather than subclassing framework internals.

What You Get

  • A processor pipeline architecture where every log call passes an event dict through an ordered list of functions (add timestamps, merge context, render output) that you configure per application
  • Built-in renderers for JSON, logfmt, and a colorized ConsoleRenderer for local development, plus the building blocks to write custom renderers
  • Native contextvars support via structlog.contextvars for binding request-scoped context (request IDs, user IDs) that automatically flows through async call stacks
  • A BoundLogger pattern that lets you bind key-value context once and reuse the resulting logger, avoiding repetitive keyword arguments on every call site
  • Drop-in interoperability with the stdlib logging module via structlog.stdlib, so structlog can sit in front of or alongside existing log handlers and third-party libraries that log through stdlib
  • Full type hints and a py.typed marker, plus testing helpers (structlog.testing.capture_logs) for asserting on structured log output in test suites

Common Use Cases

  • Emitting machine-parseable JSON logs from a production web service so a log aggregator (ELK, Loki, Datadog) can index and query fields directly instead of regex-parsing messages
  • Binding per-request context (request ID, user ID, tenant) once at the start of a request and having it automatically attached to every subsequent log line for that request, including across async boundaries via contextvars
  • Getting readable, colorized log output during local development with ConsoleRenderer while switching to JSON output in production via configuration, without changing any call sites
  • Migrating an existing codebase that logs through the stdlib logging module incrementally, using structlog’s processors on top of stdlib loggers before fully committing to structlog-native logging
  • Writing unit tests that assert specific structured log events were emitted with specific fields, using structlog.testing.capture_logs instead of parsing captured stdout

Under The Hood

Architecture

structlog is built around a processor pipeline: _config.py holds a global _Configuration object (default processors, context class, wrapper class, logger factory) that get_logger/wrap_logger consult to build a BoundLoggerBase (_base.py) around whatever underlying logger you choose. Each .info()/.warning()/etc. call constructs an event dict and threads it through the configured processor list — functions like merge_contextvars, add_log_level, TimeStamper, and a terminal renderer (ConsoleRenderer, JSONRenderer, or LogfmtRenderer in processors.py/dev.py) — before handing the result to a logger_factory (PrintLoggerFactory, or stdlib.py’s adapters for the standard library). This makes the pipeline the extension point: adding behavior means inserting or writing a new processor function, not subclassing a logger class, and contextvars.py layers request-scoped binding on top via Python’s native contextvars so context survives async/await boundaries without explicit threading.

Tech Stack

The library targets Python 3.10+ with hatchling/hatch-vcs as the build backend and VCS-derived versioning (no hardcoded version string). Runtime dependencies are minimal — only typing-extensions on Python <3.11 — keeping the core dependency-free. Optional integration modules (twisted.py) are imported defensively and degrade to None if the corresponding third-party package isn’t installed. Development tooling is uv-style dependency groups in pyproject.toml (tests, typing, docs, benchmark) rather than a separate requirements file, with tox.ini driving the full matrix across supported Python versions.

Code Quality

The repository ships an extensive test suite (over 400 test functions across tests/, covering base logging, stdlib interop, contextvars, output renderers, tracebacks, and packaging) run under pytest with --strict-markers/--strict-config and asyncio_mode = auto for async test support. Type checking is enforced via mypy with per-file overrides, linting and formatting via ruff (pre-commit hook with --fix), docstring coverage via interrogate, and spelling via codespell; CI runs a dedicated codeql-analysis.yml security scan, a zizmor.yml workflow-hardening check, and codspeed.yml for performance regression benchmarking. The codebase carries a py.typed marker and is fully type-annotated with from __future__ import annotations throughout.

What Makes It Unique

Rather than modeling logging as a class hierarchy of loggers and handlers (the stdlib’s approach), structlog models it as data transformation: a log call is just a dictionary passed through an ordered list of pure functions, which makes the pipeline trivially introspectable, testable, and reorderable. Combined with first-class contextvars integration for propagating structured context across async code, and the ability to sit transparently in front of the stdlib logging module rather than requiring wholesale replacement, this gives structlog a migration path most structured-logging libraries don’t offer.

Used by 14 apps in this directory

TypeScript
98%
MIT

Promptfoo

AI Development

26,358

An open-source CLI and library for evaluating and red-teaming LLM applications — replace trial-and-error prompt engineering with systematic evals, vulnerability scanning, and CI/CD integration.

View details
90
Repo Health
73
Technical
67
Dependency
Built with
TypeScript 98%
Updated 5 days ago
Python
99%
Apache 2.0

Rasa Open Source

AI Assistants · AI Development · Voice AI

21,353

Rasa Open Source is a Python machine learning framework for building contextual, multi-turn chatbots and voice assistants that understand natural language and maintain conversation state.

View details
62
Repo Health
78
Technical
63
Dependency
Built with
Python 99%
Updated 3 months ago
Python
57%
Other

Sentry

Analytics · Developer Tools · Monitoring

45,632

Developer-first error tracking and performance monitoring platform with AI-powered root-cause analysis across 20+ languages and frameworks.

View details
95
Repo Health
80
Technical
66
Dependency
Built with
Python 57%
TypeScript 42%
Updated 5 days ago
Python
79%
AGPL 3.0

Skyvern

AI Agents · Automation

23,257

Skyvern (YC S2023) automates browser-based workflows by pairing LLMs with computer vision, letting agents click, fill, and extract data on sites they've never seen, without brittle XPath selectors that break on every layout change.

View details
89
Repo Health
82
Technical
70
Dependency
Built with
Python 79%
TypeScript 19%
Updated 5 days ago
Python
73%
Apache 2.0

Unsloth

AI Assistants · AI Development

78,493

Run and fine-tune LLMs, diffusion, audio and embedding models on your own hardware, from a native desktop app, a browser UI, or a Python library.

View details
89
Repo Health
83
Technical
70
Dependency
Built with
Python 73%
TypeScript 22%
Updated 5 days ago

Join founders buildingwith open source

Opinionated takes, migration guides, cost-saving tips, and insights from the open source ecosystem.

Subscribe on Substack
Join 750+ subscribers