Metadata-Version: 2.5
Name: xakki-log-python
Version: 0.4.0
Summary: Structured logging library for Python — GELF/Graylog-oriented, Python port of xakki/log-laravel
Project-URL: Homepage, https://github.com/Xakki/log-python
Project-URL: Source, https://github.com/Xakki/log-python
Author: xakki
License-Expression: GPL-3.0-or-later
License-File: LICENSE
Keywords: fluent-bit,gelf,graylog,logging,structured-logging
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: System :: Logging
Classifier: Typing :: Typed
Requires-Python: >=3.11
Provides-Extra: dev
Requires-Dist: mypy>=1.11; extra == 'dev'
Requires-Dist: pytest-cov>=5.0; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.6.0; extra == 'dev'
Provides-Extra: redis
Requires-Dist: redis>=5.0; extra == 'redis'
Provides-Extra: sqlalchemy
Requires-Dist: sqlalchemy>=2.0; extra == 'sqlalchemy'
Description-Content-Type: text/markdown

# xakki-log-python

Structured JSON logging for Python, compatible with the field and type contract
of [`xakki/log-laravel`](https://github.com/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](https://pypi.org/project/xakki-log-python/):

```sh
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:

```sh
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:

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

## Quick start

```python
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:

```python
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`:

```python
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:

```python
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:

```python
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()`):

```python
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

```python
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

```python
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:

- [LoggingRules.md](https://github.com/Xakki/log-laravel/blob/main/docs/LoggingRules.md)
- [ContextFieldNaming.md](https://github.com/Xakki/log-laravel/blob/main/docs/ContextFieldNaming.md)
- [Graylog.md](https://github.com/Xakki/log-laravel/blob/main/docs/Graylog.md)
- [PhytonLog.md](https://github.com/Xakki/log-laravel/blob/main/docs/PhytonLog.md)

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.

```sh
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](https://github.com/Xakki/log-laravel/blob/main/docs/LoggingRules.md)):

* [log-laravel](https://github.com/Xakki/log-laravel) — `xakki/log-laravel`. Laravel / Monolog: custom `LogManager`, processors, redaction, SQL and queue logging.
* [log-symfony](https://github.com/Xakki/log-symfony) — `xakki/log-symfony`. PSR-3 / Symfony / Monolog 3: context enrichment, type coercion, redaction.
* [log-php](https://github.com/Xakki/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](https://github.com/Xakki/log-fluent) — `xakki/log-fluent`. Fluent Bit config bundle that ships these logs to Graylog (GELF) and Prometheus.
