Django Observe Kit
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. Inset_extra,set_context,set_tag,set_user,add_breadcrumbdata andcapture_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, soset_extra("form", {"password": x})sends the password, as do contexts and tags. It matches exact names, soset_extra("user_password", x)is sent too, and top-levelaccess_token,refresh_tokenandsignatureare sent too. Remove secrets first; adding the exact names toEXTRA_DROP_HEADERSis a backstop. A log call'sextra={"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=hunter2in a sentence, bare tokens, phone numbers, names, positional arguments such as"password %s", exception objects such asValueError({"password": ...}), and names not on the list such asclient_secret, orcsrftokenandsessionidnested in your data. - Other handlers get the original record. This includes your own handlers and Django's
djangoanddjango.serverhandlers. - Do not log
request.METAor large or sensitive objects. Only someMETAentries are treated, and underrunserverit also holds the process environment. Sequences are opened, so logging a Django paginatorPageruns its query (and inextra, 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 aspasswordandtokenas[Filtered], but other names such asclient_secretorcsrfmiddlewaretoken, and credentials inside strings (including a URL query in a header value such asReferer), are stored as given. - Sentry scrubbing has gaps, including attachments, phone numbers and bare
token=...in free text, and parameter names such asclient_secretorcsrfmiddlewaretoken. 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 isNONE), 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-levelbyteskey (extra={b"password": ...}) reaches Sentry as is. - Do not rely on
__repr__,__str__or__sentry_repr__to hide a secret. In Sentry log data,%sand an object logged as the message callstr(), asloggingand the plain Sentry SDK do. An object inextrais generally shown as the SDK would show it, by__sentry_repr__orrepr(), 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 andstr(), 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
INFOand 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 lazyQuerySetpassed directly inextrais not run by the Sentry cleaning, but a paginatorPagethere 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, andpassword/tokenkeys nested inside a local are sent as is. If your app callssentry_sdk.init()itself afterinit_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_completeanddjango.requestlogs and, in Sentry, inrequest.url, thehttp.pathtag 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_completeevent. - Tracing: OpenTelemetry traces and log export over OTLP/HTTP, and an
X-Trace-Idresponse header. Incoming trace headers are ignored unlessTRUST_INCOMING_TRACE_CONTEXTis 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-sdk2.x only (>=2.66.1,<3, installed as a dependency)- For the
wagtailextra, 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
urllib3request 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 arequestshook. - A
LoggerProviderwithshutdown_on_exit=True(the default, including the oneinit_tracing()creates) also exports them at a normal exit. With an unreachable collector, exit can take aboutOTEL_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: lowerOTEL_EXPORTER_OTLP_TIMEOUTor allow more time to stop. - A process that ends without running
atexithandlers loses its queued records, for example amultiprocessingfork child (which leaves throughos._exit) or a process killed by an unhandledSIGTERM.
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.comgivesacme, butexample.co.ukalso givesexample) and that label is notwwworlocalhost; - 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
- Configuration reference
- Middleware reference
- PII sanitization and known limitations
- HyperDX quickstart
- Changelog
- Security policy: report vulnerabilities privately
Contributing
See CONTRIBUTING.md for development setup and tests. Maintainers: see the release checklist.
License
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)
| 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)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| 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 logRelease 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 logSecurity 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.
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 logA 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.