structlog

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

Library
PyPI
v26.1.0
4,965 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 →
76 /100 Good
Development Activity 76
Maintenance 64
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
56%
Other

agenta

AI Development · Developer Tools · Devops

4,788

The open-source LLMOps platform unifying prompt engineering, evaluation, and observability for teams building reliable LLM applications.

View details
91
Repo Health
77
Technical
67
Dependency
Built with
TypeScript 56%
Python 39%
Updated 5 days ago
Python
89%
Apache 2.0

Apache Airflow

Data Engineering

46,995

Define, schedule, and monitor complex data workflows as Python code — with a powerful UI, 80+ provider integrations, and battle-tested scalability across thousands of production deployments.

View details
96
Repo Health
89
Technical
64
Dependency
Built with
Python 89%
Updated 4 days ago
Python
55%
Other

authentik

Authentication · Security

25,758

The self-hosted Identity Provider that replaces Okta, Auth0, and Entra ID with a unified SSO platform supporting SAML, OAuth2/OIDC, LDAP, RADIUS, and WebAuthn.

View details
92
Repo Health
81
Technical
66
Dependency
Built with
Python 55%
TypeScript 36%
Updated 4 days ago
Go
59%
Apache 2.0

Cog

AI Development · Developer Tools · Devops

9,484

An open-source CLI that packages machine learning models into standard, production-ready Docker containers — no Dockerfile wrangling, no CUDA version hell.

View details
85
Repo Health
88
Technical
69
Dependency
Built with
Go 59%
Rust 17%
HTML 13%
Updated 1 weeks ago
Python
63%
BSD 3

Flagsmith

Ab Testing Experimentation · Developer Tools · Devops

6,577

Open-source feature flagging, remote config, and A/B/multivariate testing platform for web, mobile, and server-side apps — self-host or use the hosted SaaS.

View details
90
Repo Health
82
Technical
63
Dependency
Built with
Python 63%
TypeScript 31%
Updated 6 days ago
TypeScript
51%
AGPL 3.0

Glean

Bookmarks Archiving · Knowledge Management

868

Self-hosted RSS reader and personal knowledge management tool with MCP server integration for AI assistant connectivity.

View details
73
Repo Health
75
Technical
70
Dependency
Built with
TypeScript 51%
Python 45%
Updated 1 weeks ago
Python
69%
MIT

Langflow

AI Agents · AI Development

155,319

Build, test, and deploy AI agents and RAG workflows visually with native API and MCP server export.

View details
90
Repo Health
85
Technical
65
Dependency
Built with
Python 69%
TypeScript 22%
Updated 4 days ago
Python
65%
Apache 2.0

Polar

Developer Tools · Ecommerce · Invoicing Finance

10,293

Open source payments infrastructure that turns software into a business — subscriptions, usage-based billing, digital products, and merchant-of-record compliance in one platform.

View details
90
Repo Health
82
Technical
66
Dependency
Built with
Python 65%
TypeScript 28%
Updated 4 days ago
Python
55%
Other

PostHog

Ab Testing Experimentation · Analytics · Developer Tools

39,975

The all-in-one open source product platform combining analytics, session replay, feature flags, error tracking, AI observability, and a built-in data warehouse in a single self-hostable stack.

View details
92
Repo Health
80
Technical
65
Dependency
Built with
Python 55%
TypeScript 36%
Updated 4 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