Skip to main content

xakki-log-python

Structured JSON logging for Python, compatible with the field and type contract of xakki/log-laravel and intended for stdout → fluent-bit → Graylog/GELF pipelines.

Distribution: xakki-log-python (formerly xakki-pylog); import name: log_python (formerly pylog).

The core uses only the Python standard library. Redis and SQLAlchemy support are optional extras.

The release version has one editable source: [project].version in pyproject.toml. LOGGER_VER reads the installed distribution metadata, log_python.__version__ aliases it, and every record emits it as extra.log_ver.

Requirements

  • Python 3.11+
  • No runtime dependencies for the core package

Installation

The package is published on PyPI:

pip install xakki-log-python
# optional integrations
pip install 'xakki-log-python[redis]'
pip install 'xakki-log-python[sqlalchemy]'

The same package name works with other package managers:

uv add xakki-log-python
poetry add xakki-log-python
pdm add xakki-log-python
pipenv install xakki-log-python

Extras use the same syntax, e.g. uv add 'xakki-log-python[redis]'.

To install the unreleased development version straight from Git:

pip install git+https://github.com/Xakki/log-python

Quick start

import logging
import log_python

log_python.setup()

logger = logging.getLogger("orders")
logger.info(
    "order paid",
    extra={"context": {"order_id": "42", "order_money": "19.99"}},
)

order_id is emitted as an integer and order_money as a float according to the shared context field naming contract. Every record also receives log_type, file, request_id, stable process metadata and, at warning or above, a bounded trace.

log_python.setup() configures one idempotent root StreamHandler. It preserves unrelated handlers and writes one newline-terminated JSON object per event.

Configuration

PylogConfig.from_env() reads a startup snapshot:

Variable Purpose Default
APP_NAME extra.app_name unset
APP_ENV extra.app_env unset
APP_VERSION extra.app_ver unset
LOG_TIER extra.tier (web, api, worker, cron) unset
RELEASE_TAG release/build id unset
RELEASE_TIME release time unset
LOG_MESSAGE_LIMIT source message character limit 3024
LOG_ALLOW_MEMORY add process memory fields false
LOG_SNAKE_CASE normalize context keys before coercion false
LOG_CAPTURE_HANDLERS install chained uncaught-exception hooks false

Boolean parsing accepts 1/true/yes/on and 0/false/no/off (case-insensitive). Invalid values raise ValueError during configuration instead of silently changing behavior.

Programmatic configuration:

from log_python import ExtraConfig, PylogConfig, setup

config = PylogConfig(
    extra=ExtraConfig(
        app_name="orders",
        app_env="prod",
        app_ver="2026.08.13",
        tier="worker",
    ),
    capture_handlers=True,
)
setup(config=config)

Available formatters are JsonFormatter (default), LineFormatter, and ConsoleFormatter:

log_python.setup(formatter="console", replace=True)

Context and request correlation

Bound context is isolated with contextvars, so concurrent threads and async tasks do not overwrite one another:

from log_python import bind, bound_context, clear, set_request_id

set_request_id(incoming_request_id)
bind(user_id=7)

with bound_context(order_id=42):
    logger.info("order loaded")

clear()

Web middleware can call remote_ip(value). Queue workers should call reset_request_id() and clear() between jobs.

Exceptions and redaction

Use normal stdlib exception logging:

try:
    run_job()
except RuntimeError:
    logger.exception("job failed", extra={"context": {"job_id": 42}})

Exception class, sanitized message, code, origin and coalesced trace are emitted as structured context. Sensitive keys and recognizable Bearer/Basic tokens, JWTs, key/value credentials and URL passwords are redacted before serialization. skipTrace can suppress trace collection for a specific event and is never emitted itself.

When LOG_CAPTURE_HANDLERS=true (or setup enables capture explicitly), log_python chains the process/thread exception hooks and warnings.showwarning. Uncaught exceptions get log_type=exception; runtime warnings get log_type=trigger. Python cannot reliably turn native crashes into structured JSON, so supervisors and faulthandler remain the fallback for those failures.

Optional integrations

Redis

log_python.handlers.redis.RedisHandler accepts any redis-py-compatible client, uses LPUSH, and applies LTRIM in the same transaction when cap_size > 0. It stores exactly the result of its configured formatter, so attach JsonFormatter (or reuse the formatter installed by log_python.setup()):

from redis import Redis
from log_python.handlers.redis import RedisHandler

handler = RedisHandler(Redis.from_url("redis://localhost"), key="logs", cap_size=10_000)
handler.setFormatter(log_python.JsonFormatter(log_python.PylogConfig.from_env()))

SQLAlchemy

from log_python.integrations.sqlalchemy import install_sqlalchemy_logging

install_sqlalchemy_logging(
    engine,
    select_threshold_ms=200,
    all_threshold_ms=500,
    include_bindings=False,  # keep disabled in production
)

The integration emits db_table, db_time_ms, db_bindings, sql_type, and tag=sql. Telescope queries are ignored; long or numerous bindings are not expanded. Bindings are disabled by default and pass through the secret redactor before serialization when explicitly enabled.

Worker heartbeat

from log_python import Heartbeat

heartbeat = Heartbeat(logging.getLogger("worker"), name="default", interval=120)
heartbeat.start()
# ...
heartbeat.stop(status=0)

Wire contract

The normative, language-independent specification remains in the reference repository and is not duplicated here:

The JSON formatter provides lowercase level_name, Monolog-compatible numeric level values (100–600), RFC-3339 timestamps with timezone and microseconds, canonical app_name/app_env extras, one coalesced trace field, and iterative UTF-8-aware trimming to the configured wire budget (1400 bytes by default) without dropping the required process-extra fields.

Development

The repository is Docker-only. Do not run Python tooling directly on the host.

make docker-build
make deps-i
make test          # ruff format/check + mypy --strict + pytest
make build
make test-install  # uv, Poetry, PDM, Pipenv and pip

Run make help for all targets.

Related projects

Sibling logging libraries sharing one field contract (Logging Rules):

  • log-laravel — xakki/log-laravel. Laravel / Monolog: custom LogManager, processors, redaction, SQL and queue logging.
  • log-symfony — xakki/log-symfony. PSR-3 / Symfony / Monolog 3: context enrichment, type coercion, redaction.
  • log-php — xakki/log-php. Plain PHP (no framework, PSR-3; PHP 5.6+ on branch master56): error/exception catcher with pluggable storages.
  • log-fluent — xakki/log-fluent. Fluent Bit config bundle that ships these logs to Graylog (GELF) and Prometheus.

Metadata

Release files for xakki-log-python 0.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for xakki-log-python 0.4.0
File Size Uploaded Provenance Actions
xakki_log_python-0.4.0.tar.gz 163.5 kB With provenance Details for xakki_log_python-0.4.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for xakki-log-python 0.4.0
File Interpreter ABI Platform Actions
xakki_log_python-0.4.0-py3-none-any.whl Python 3 none any Details for xakki_log_python-0.4.0-py3-none-any.whl

Total release size: 226.5 kB

Release files / xakki_log_python-0.4.0.tar.gz

Download URL xakki_log_python-0.4.0.tar.gz
Size 163.5 kB
Tags Source
SHA-256 checksum
How to use checksums
60d383c936ed3b42e327d8c8c27440e8f40b6ebf484f5e61002ed15e38f855a5
BLAKE2b-256 checksum
How to use checksums
597b6ace17904795f9cea7504699a47563c2ecebc581d825612d5925b02e9dd6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 5, 2026.

Transparency log

Release files / xakki_log_python-0.4.0-py3-none-any.whl

Download URL xakki_log_python-0.4.0-py3-none-any.whl
Size 62.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
62136ac09d754797ee81112c2602fc60b712c00be3cbd2670790bdc5996f0281
BLAKE2b-256 checksum
How to use checksums
009f0958f934a9ff8d5327c460a6d09cbc1a363ceb8fecd86ef15737a63e1197
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 5, 2026.

Transparency log

Security for xakki-log-python 0.4.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for xakki_log_python-0.4.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 5, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.4.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page