Skip to main content

Django Observe Kit

CI Python 3.10+ Django 5.2+ License: MIT

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.
  • 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 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

Installation

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.

# 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:

# 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.

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

In another terminal:

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.

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, so set OBSERVE_KIT_METRICS_AUTH=token and OBSERVE_KIT_METRICS_TOKEN to keep /metrics protected.

# 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")
# 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); 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, 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:

# 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:

# 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:

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 instead.)

Audit rows are protected only against ordinary ORM calls.

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

Contributing

See CONTRIBUTING.md for development setup and tests. Maintainers: see the release checklist.

License

MIT

Metadata

Release files for django-observe-kit 0.1.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 django-observe-kit 0.1.0
File Size Uploaded Provenance Actions
django_observe_kit-0.1.0.tar.gz 127.1 kB With provenance Details for django_observe_kit-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for django-observe-kit 0.1.0
File Interpreter ABI Platform Actions
django_observe_kit-0.1.0-py3-none-any.whl Python 3 none any Details for django_observe_kit-0.1.0-py3-none-any.whl

Total release size: 265.7 kB

Release files / django_observe_kit-0.1.0.tar.gz

Download URL django_observe_kit-0.1.0.tar.gz
Size 127.1 kB
Tags Source
SHA-256 checksum
How to use checksums
8de7049a060546e772b68200096445d67b70d04bf5e3ab98e7c0d8caf7603ac3
BLAKE2b-256 checksum
How to use checksums
e4a50f328173bdae97e3aa378eda44ab72d03abb7cab91fa7024a55dcce0aea0
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 28, 2026.

Transparency log

Release files / django_observe_kit-0.1.0-py3-none-any.whl

Download URL django_observe_kit-0.1.0-py3-none-any.whl
Size 138.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
beca128b9965c064f377bb483dc250faca197d548500592dc096b3475d40791d
BLAKE2b-256 checksum
How to use checksums
4e3d52e9c31a4d1a676b2a389fba14b5346c3870bea3037dcab70d0c0a398059
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 28, 2026.

Transparency log

Security for django-observe-kit 0.1.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 django_observe_kit-0.1.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 28, 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.1.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