Metadata-Version: 2.4
Name: django-observe-kit
Version: 0.1.0
Summary: Drop-in observability toolkit for Django/DRF/Wagtail
Author: Wiphoo (Terng) Methachawalit
License-Expression: MIT
Project-URL: Homepage, https://github.com/wiphoo/django-observe-kit
Project-URL: Documentation, https://github.com/wiphoo/django-observe-kit/blob/main/docs/README.md
Project-URL: Repository, https://github.com/wiphoo/django-observe-kit
Project-URL: Issues, https://github.com/wiphoo/django-observe-kit/issues
Project-URL: Changelog, https://github.com/wiphoo/django-observe-kit/blob/main/CHANGELOG.md
Keywords: django,drf,wagtail,observability,opentelemetry,prometheus,sentry,tracing,metrics,logging,pii
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Web Environment
Classifier: Framework :: Django
Classifier: Framework :: Django :: 5.2
Classifier: Framework :: Django :: 6.0
Classifier: Framework :: Django :: 6.1
Classifier: Framework :: Wagtail
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: System :: Monitoring
Classifier: Topic :: System :: Logging
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: Django>=5.2
Requires-Dist: djangorestframework>=3.16
Requires-Dist: prometheus-client>=0.26.0
Requires-Dist: opentelemetry-sdk>=1.38.0
Requires-Dist: opentelemetry-exporter-otlp>=1.44.0
Requires-Dist: python-json-logger>=3.0
Requires-Dist: sentry-sdk<3,>=2.66.1
Provides-Extra: wagtail
Requires-Dist: wagtail>=7.4.2; extra == "wagtail"
Dynamic: license-file

# Django Observe Kit

[![CI](https://github.com/wiphoo/django-observe-kit/actions/workflows/ci.yml/badge.svg)](https://github.com/wiphoo/django-observe-kit/actions/workflows/ci.yml)
[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
[![Django 5.2+](https://img.shields.io/badge/django-5.2+-green.svg)](https://www.djangoproject.com/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/wiphoo/django-observe-kit/blob/main/LICENSE)

Drop-in observability toolkit for Django/DRF/Wagtail: request context, structured JSON logging, OpenTelemetry tracing, Prometheus metrics, Sentry, and audit logs, with PII rules for the data Observe Kit collects.

**Status: beta.** This is a 0.x release, and its API and defaults may change between minor versions.

## What is not sanitized

PII scrubbing is a safety net, not a guarantee. Keep secrets and personal data out of what you log or send. In particular:

- **Passwords and tokens you attach to Sentry yourself can be sent as is, with default settings and at `SENSITIVE`.** In `set_extra`, `set_context`, `set_tag`, `set_user`, `add_breadcrumb` data and `capture_message(extras=...)`, Observe Kit does not redact values by credential name. `set_extra("password", x)` is sent as `[Filtered]` only because the Sentry SDK's own scrubber knows that top-level name. That scrubber does not look inside nested data, so `set_extra("form", {"password": x})` sends the password, as do contexts and tags. It matches exact names, so `set_extra("user_password", x)` is sent too, and top-level `access_token`, `refresh_token` and `signature` are sent too. Remove secrets first; adding the exact names to `EXTRA_DROP_HEADERS` is a backstop. A log call's `extra={"password": x}` is different: the log rules redact it, nested too. [Details](https://github.com/wiphoo/django-observe-kit/blob/main/docs/pii.md#data-you-attach-to-sentry-yourself).
- **Log records are only partly cleaned.** On the outputs Observe Kit configures (its JSON console output and its OpenTelemetry log handler), listed field names are dropped, masked or redacted, emails are masked and URL credentials are scrubbed. Other free text is written as given: `password=hunter2` in a sentence, bare tokens, phone numbers, names, positional arguments such as `"password %s"`, exception objects such as `ValueError({"password": ...})`, and names not on the list such as `client_secret`, or `csrftoken` and `sessionid` nested in your data.
- **Other handlers get the original record.** This includes your own handlers and Django's `django` and `django.server` handlers.
- **Do not log `request.META` or large or sensitive objects.** Only some `META` entries are treated, and under `runserver` it also holds the process environment. Sequences are opened, so logging a Django paginator `Page` runs its query (and in `extra`, writes every row).
- **Sanitizing costs CPU.** In our microbenchmarks a record took roughly 5 to 11 times the CPU time of unsanitized JSON console output, and each output pays it again. There is no limit on the total text size.
- **The audit log redacts only some credential names.** `audit()` stores values under names such as `password` and `token` as `[Filtered]`, but other names such as `client_secret` or `csrfmiddlewaretoken`, and credentials inside strings (including a URL query in a header value such as `Referer`), are stored as given.
- **Sentry scrubbing has gaps**, including attachments, phone numbers and bare `token=...` in free text, and parameter names such as `client_secret` or `csrfmiddlewaretoken`. Source code lines around each stack frame are sent. Cron check-ins (`sentry_sdk.monitor`) are still sent.
- **Sentry data made from log records gets the log rules, with their gaps.** After `init_sentry()` (unless the Sentry level is `NONE`), breadcrumbs and events the SDK builds from log calls are cleaned much like the console output, so the log gaps above apply to them too, and a top-level `bytes` key (`extra={b"password": ...}`) reaches Sentry as is.
- **Do not rely on `__repr__`, `__str__` or `__sentry_repr__` to hide a secret.** In Sentry log data, `%s` and an object logged as the message call `str()`, as `logging` and the plain Sentry SDK do. An object in `extra` is generally shown as the SDK would show it, by `__sentry_repr__` or `repr()`, so a secret that these print is sent unless the log rules or the text scrubbing catch it. An object in which the log rules would change something, or which they cannot check completely, is sent as `[Filtered]`. So masking a secret in `__str__` does not help if `__repr__` shows it. The console and OpenTelemetry log outputs are different: they show dataclass fields and `str()`, whatever a custom `__repr__` hides.
- **Data not built from a log record gets the Sentry scrubbing only**, not the log cleaning. If your app calls `sentry_sdk.init()` itself, none of Observe Kit's cleaning applies.
- **Sentry cleaning runs inside your log calls.** It is synchronous, runs for every log record the SDK captures (by default `INFO` and above, as breadcrumbs), and happens before the SDK truncates anything. In our tests a 1 MB string full of URLs took about 1.5 to 4 seconds, and 4 MB about 6 to 7 seconds. A lazy `QuerySet` passed directly in `extra` is not run by the Sentry cleaning, but a paginator `Page` there still runs its query, and the console and OpenTelemetry log outputs run both and write the rows. One passed as a `%` argument is run, and its rows can reach Sentry in the message.
- **Stack-frame local variables are not sent by default.** If you turn them on with `init_sentry(..., include_local_variables=True)`, values such as names, `client_secret`, and `password` / `token` keys nested inside a local are sent as is. If your app calls `sentry_sdk.init()` itself after `init_sentry()`, that client replaces it: Observe Kit's scrubbing is gone and the SDK's defaults apply, which send local variables.
- **Trace spans are only partly cleaned.** On the spans Observe Kit writes, emails are masked and credential query values in URLs and paths are redacted. Among what is exported as is: tokens in path segments (`/reset/<token>/`), `token=...` and `?token=...` in text with no URL or path before it, secrets written as literals in source lines that appear in exception stack traces, and the spans, attributes and events your own code creates (including exceptions the OpenTelemetry SDK records on your child spans).
- **Tokens in URL paths go further than spans.** They also appear in the `request_complete` and `django.request` logs and, in Sentry, in `request.url`, the `http.path` tag and, for a URL that matches no route, the transaction name.

Read all [known limitations](https://github.com/wiphoo/django-observe-kit/blob/main/docs/pii.md#known-limitations) before relying on it.

## Features

- **Request context and logging:** JSON logs with request fields, including a `request_complete` event.
- **Tracing:** OpenTelemetry traces and log export over OTLP/HTTP, and an `X-Trace-Id` response header. Incoming trace headers are ignored unless `TRUST_INCOMING_TRACE_CONTEXT` is on.
- **Metrics:** Prometheus request, latency and database metrics on `/metrics`.
- **Sentry:** error and transaction scrubbing at a configurable PII level. Sentry metrics and logs are disabled because they would bypass it.
- **DRF, audit log and Wagtail:** optional integrations.

## Requirements

- Python 3.10 or later
- Django 5.2 or later and Django REST framework 3.16 or later (installed as a dependency)
- `sentry-sdk` 2.x only (`>=2.66.1,<3`, installed as a dependency)
- For the `wagtail` extra, Python 3.11.5 or later is recommended: older interpreters resolve [releases with security advisories](https://github.com/wiphoo/django-observe-kit/blob/main/docs/pii.md#wagtail-extra-on-older-python)

## Installation

```bash
pip install django-observe-kit
```

For the Wagtail integration, install `"django-observe-kit[wagtail]"` instead.

## Quickstart

**1. Settings.** Add this to the end of your project's `settings.py`. Keep the middleware in this order, and after Django's `AuthenticationMiddleware` so that logs include the user ID.

```python
# settings.py (append)
import os

INSTALLED_APPS += ["observe_kit"]

MIDDLEWARE += [
    "observe_kit.otel.middleware.TraceContextMiddleware",
    "observe_kit.logging.middleware.RequestLoggingMiddleware",
    "observe_kit.metrics.middleware.PrometheusRequestMiddleware",
    "observe_kit.context_middleware.RequestContextMiddleware",
    "observe_kit.context_middleware.UserLoggingContextMiddleware",
    "observe_kit.sentry.middleware.SentryContextMiddleware",
]

OBSERVE_KIT = {
    # Enables tracing. Traces and logs go to an OTLP/HTTP collector.
    "SERVICE_NAME": "my-app",
    "OTEL_ENDPOINT": "http://localhost:4318",
    # Salt for hashed PII values; set a secret value per environment.
    "PII_HASH_SALT": os.environ.get("PII_HASH_SALT", ""),
    # /metrics is open to anyone unless you set this.
    "METRICS_AUTH": "token",
    "METRICS_TOKEN": os.environ.get("METRICS_TOKEN"),
}
```

With `OBSERVE_KIT` set, logging, tracing and Sentry are initialised at startup. Sentry starts when the `SENTRY_DSN` environment variable (or setting) is present. If no collector is reachable at `OTEL_ENDPOINT`, the exporter logs errors and commands such as `check` and `migrate` are slow to exit (in our tests with default settings each took about 7 to 11 seconds in total, against about 1 second without tracing, and it can be longer); remove `SERVICE_NAME` to run without tracing, and make sure `OTEL_SERVICE_NAME` is not set.

**2. Metrics URL.** Include `observe_kit.urls`, which serves `/metrics`:

```python
# urls.py
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path("admin/", admin.site.urls),
    path("", include("observe_kit.urls")),
]
```

**3. Run it.**

```bash
export PII_HASH_SALT=change-me METRICS_TOKEN=change-me
python manage.py check
python manage.py runserver
```

In another terminal:

```bash
curl -H "Authorization: Bearer change-me" http://127.0.0.1:8000/metrics
```

The server prints a JSON `request_complete` log line for the request. Its `tenant_id` is `null`, because an IP-address host never gives a [tenant](#tenant-ids).

### Manual initialisation

To initialise from code instead, leave out the whole `OBSERVE_KIT` dict and call the functions from an `AppConfig.ready()`, which runs after Django has configured its logging. Other options come from [environment variables or defaults](https://github.com/wiphoo/django-observe-kit/blob/main/docs/configuration.md), so set `OBSERVE_KIT_METRICS_AUTH=token` and `OBSERVE_KIT_METRICS_TOKEN` to keep `/metrics` protected.

```python
# mysite/apps.py
import os

from django.apps import AppConfig


class MySiteConfig(AppConfig):
    name = "mysite"  # your project package or one of your apps

    def ready(self) -> None:
        from observe_kit import configure_logging, init_sentry, init_tracing

        configure_logging(level="INFO")
        init_tracing(service_name="my-app", endpoint="http://localhost:4318")
        if os.environ.get("SENTRY_DSN"):
            init_sentry(dsn=os.environ["SENTRY_DSN"], environment="production")
```

```python
# manual initialisation (append to settings.py)
INSTALLED_APPS += ["mysite"]
```

### Exporting logs at shutdown

For the log handler that `init_tracing()` adds, **`handler.flush()`, `logging.shutdown()` and `logging.config.dictConfig()` do not export queued records.** (Flushing there could keep a process from ever exiting.)

- Queued records are still exported periodically.
- Records logged while telemetry is being exported (such as `urllib3` request lines and exporter errors) are not sent through this handler, which prevents the direct export loop (but see [the Sentry case](#debug-logging-with-sentry-and-a-failing-collector)); your other handlers still receive them. This also skips anything else logged on the exporting thread during that call, for example by a `requests` hook.
- A `LoggerProvider` with `shutdown_on_exit=True` (the default, including the one `init_tracing()` creates) also exports them at a normal exit. With an unreachable collector, exit can take about `OTEL_EXPORTER_OTLP_TIMEOUT` (default 10 seconds) or longer. That **may exceed a 10-second container stop timeout**, so that the process is killed before it finishes: lower `OTEL_EXPORTER_OTLP_TIMEOUT` or allow more time to stop.
- A process that ends without running `atexit` handlers **loses its queued records**, for example a `multiprocessing` fork child (which leaves through `os._exit`) or a process killed by an unhandled `SIGTERM`.

### `DEBUG` logging with Sentry and a failing collector

**With the root log level at `DEBUG`, Sentry enabled and a collector that fails (it answered 503 or refused the connection in our tests), an idle process keeps feeding itself:** the exporter's error becomes a Sentry error event, sending that event makes `urllib3` log a `DEBUG` line, which is exported again and fails again. In our tests an idle process sent about 4 Sentry events every 30 seconds for as long as we watched (2 minutes), which **uses your Sentry quota**. It did not happen at `INFO`, without Sentry, or with a collector that accepted the exports. Do not run the root logger at `DEBUG` in this setup, or keep `urllib3` quiet, which stopped it in our tests: `logging.getLogger("urllib3").setLevel(logging.INFO)`.

## Tenant IDs

Observe Kit attaches a tenant ID to logs, spans, metric labels and audit rows. It is `request.tenant.id` if your code set `request.tenant` before Observe Kit reads it, otherwise the `X-Tenant-ID` header when you [trust it](https://github.com/wiphoo/django-observe-kit/blob/main/docs/configuration.md#request-handling), otherwise **the first label of the host name**:

- only if the host has three or more dot-separated labels (`acme.example.com` gives `acme`, but `example.co.uk` also gives `example`) and that label is not `www` or `localhost`;
- never from an IP-address host;
- with its case kept, and only if the label matches `[A-Za-z0-9._:-]{1,128}`; otherwise the host gives no tenant (the label is not truncated).

The host is **controlled by the client** (within what `ALLOWED_HOSTS` allows), so **do not use this tenant ID for authorization**. `request.tenant.id` is not checked, so it can be longer than the declared maximum of `AuditLog.tenant_id`, 128 characters. On PostgreSQL, `audit()` then raises and writes no row.

## Optional integrations

**DRF** (view-set action names on spans and routes, and an exception handler). Add to `settings.py` after the Quickstart block:

```python
# DRF (append)
INSTALLED_APPS += ["rest_framework"]
MIDDLEWARE.insert(
    MIDDLEWARE.index("observe_kit.sentry.middleware.SentryContextMiddleware"),
    "observe_kit.drf.integration.DRFIntegrationMiddleware",
)
REST_FRAMEWORK = {"EXCEPTION_HANDLER": "observe_kit.drf.observed_exception_handler"}
```

**Audit log.** Add the app, then run `python manage.py migrate`:

```python
# audit log (append)
INSTALLED_APPS += ["observe_kit.audit"]
```

Logins and logouts are then recorded. Record your own events with `audit()`. Its first positional argument is the **actor** (a saved user, or `None`), not the action:

```python
from observe_kit.audit import audit


def approve_invoice(request, invoice):
    audit(
        request.user,  # actor: must be logged in; pass None for an anonymous request
        "invoice.approve",
        obj=invoice,
        extra={"reason": "monthly close"},
        request=request,
    )
```

**On PostgreSQL, some values make `audit()` raise and write no row:** an `action` or tenant ID longer than 128 characters, an `object_id` (from `obj.pk`) longer than 256, an `obj` whose class name is longer than 128, or a NUL or lone surrogate character in the action, tenant ID or object ID. They are not cut, because a cut value could point a row at another tenant or object. Check values your application passes in. (`user_agent` and `remote_addr` are [cut or cleaned](https://github.com/wiphoo/django-observe-kit/blob/main/docs/pii.md#audit-sink) instead.)

Audit rows are protected only against [ordinary ORM calls](https://github.com/wiphoo/django-observe-kit/blob/main/docs/pii.md#audit-sink).

**Wagtail.** In an existing Wagtail project with the audit log enabled, add `"observe_kit.wagtail_integration"` to `INSTALLED_APPS` to audit and count page publish, unpublish and delete.

## Documentation

- [Configuration reference](https://github.com/wiphoo/django-observe-kit/blob/main/docs/configuration.md)
- [Middleware reference](https://github.com/wiphoo/django-observe-kit/blob/main/docs/middleware.md)
- [PII sanitization and known limitations](https://github.com/wiphoo/django-observe-kit/blob/main/docs/pii.md)
- [HyperDX quickstart](https://github.com/wiphoo/django-observe-kit/blob/main/docs/HYPERDX_QUICKSTART.md)
- [Changelog](https://github.com/wiphoo/django-observe-kit/blob/main/CHANGELOG.md)
- [Security policy](https://github.com/wiphoo/django-observe-kit/blob/main/SECURITY.md): report vulnerabilities privately

## Contributing

See [CONTRIBUTING.md](https://github.com/wiphoo/django-observe-kit/blob/main/CONTRIBUTING.md) for development setup and tests. Maintainers: see the [release checklist](https://github.com/wiphoo/django-observe-kit/blob/main/docs/releasing.md).

## License

[MIT](https://github.com/wiphoo/django-observe-kit/blob/main/LICENSE)
