django-observe-kit 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. django_observe_kit-0.1.0/LICENSE +21 -0
  2. django_observe_kit-0.1.0/PKG-INFO +269 -0
  3. django_observe_kit-0.1.0/README.md +227 -0
  4. django_observe_kit-0.1.0/pyproject.toml +158 -0
  5. django_observe_kit-0.1.0/setup.cfg +4 -0
  6. django_observe_kit-0.1.0/src/django_observe_kit.egg-info/PKG-INFO +269 -0
  7. django_observe_kit-0.1.0/src/django_observe_kit.egg-info/SOURCES.txt +58 -0
  8. django_observe_kit-0.1.0/src/django_observe_kit.egg-info/dependency_links.txt +1 -0
  9. django_observe_kit-0.1.0/src/django_observe_kit.egg-info/requires.txt +10 -0
  10. django_observe_kit-0.1.0/src/django_observe_kit.egg-info/top_level.txt +1 -0
  11. django_observe_kit-0.1.0/src/observe_kit/__init__.py +82 -0
  12. django_observe_kit-0.1.0/src/observe_kit/apps.py +178 -0
  13. django_observe_kit-0.1.0/src/observe_kit/audit/__init__.py +25 -0
  14. django_observe_kit-0.1.0/src/observe_kit/audit/admin.py +20 -0
  15. django_observe_kit-0.1.0/src/observe_kit/audit/apps.py +16 -0
  16. django_observe_kit-0.1.0/src/observe_kit/audit/migrations/0001_initial.py +78 -0
  17. django_observe_kit-0.1.0/src/observe_kit/audit/migrations/__init__.py +0 -0
  18. django_observe_kit-0.1.0/src/observe_kit/audit/models.py +73 -0
  19. django_observe_kit-0.1.0/src/observe_kit/audit/signals.py +22 -0
  20. django_observe_kit-0.1.0/src/observe_kit/audit/utils.py +182 -0
  21. django_observe_kit-0.1.0/src/observe_kit/checks.py +35 -0
  22. django_observe_kit-0.1.0/src/observe_kit/conf.py +62 -0
  23. django_observe_kit-0.1.0/src/observe_kit/context.py +102 -0
  24. django_observe_kit-0.1.0/src/observe_kit/context_middleware.py +246 -0
  25. django_observe_kit-0.1.0/src/observe_kit/drf/__init__.py +9 -0
  26. django_observe_kit-0.1.0/src/observe_kit/drf/exception_handler.py +37 -0
  27. django_observe_kit-0.1.0/src/observe_kit/drf/integration.py +111 -0
  28. django_observe_kit-0.1.0/src/observe_kit/log_sanitize.py +430 -0
  29. django_observe_kit-0.1.0/src/observe_kit/logging/__init__.py +11 -0
  30. django_observe_kit-0.1.0/src/observe_kit/logging/config.py +159 -0
  31. django_observe_kit-0.1.0/src/observe_kit/logging/filters.py +82 -0
  32. django_observe_kit-0.1.0/src/observe_kit/logging/middleware.py +31 -0
  33. django_observe_kit-0.1.0/src/observe_kit/metrics/__init__.py +32 -0
  34. django_observe_kit-0.1.0/src/observe_kit/metrics/db.py +64 -0
  35. django_observe_kit-0.1.0/src/observe_kit/metrics/middleware.py +39 -0
  36. django_observe_kit-0.1.0/src/observe_kit/metrics/prometheus.py +263 -0
  37. django_observe_kit-0.1.0/src/observe_kit/otel/__init__.py +4 -0
  38. django_observe_kit-0.1.0/src/observe_kit/otel/config.py +403 -0
  39. django_observe_kit-0.1.0/src/observe_kit/otel/middleware.py +358 -0
  40. django_observe_kit-0.1.0/src/observe_kit/otel/sanitize.py +98 -0
  41. django_observe_kit-0.1.0/src/observe_kit/pii_rules.py +566 -0
  42. django_observe_kit-0.1.0/src/observe_kit/proxies.py +45 -0
  43. django_observe_kit-0.1.0/src/observe_kit/py.typed +0 -0
  44. django_observe_kit-0.1.0/src/observe_kit/sentry/__init__.py +4 -0
  45. django_observe_kit-0.1.0/src/observe_kit/sentry/config.py +3049 -0
  46. django_observe_kit-0.1.0/src/observe_kit/sentry/log_objects.py +238 -0
  47. django_observe_kit-0.1.0/src/observe_kit/sentry/logs.py +123 -0
  48. django_observe_kit-0.1.0/src/observe_kit/sentry/middleware.py +49 -0
  49. django_observe_kit-0.1.0/src/observe_kit/sentry/scrub/__init__.py +15 -0
  50. django_observe_kit-0.1.0/src/observe_kit/sentry/scrub/constants.py +21 -0
  51. django_observe_kit-0.1.0/src/observe_kit/sentry/scrub/decode.py +99 -0
  52. django_observe_kit-0.1.0/src/observe_kit/sentry/scrub/emails.py +248 -0
  53. django_observe_kit-0.1.0/src/observe_kit/sentry/scrub/locate.py +313 -0
  54. django_observe_kit-0.1.0/src/observe_kit/settings.py +348 -0
  55. django_observe_kit-0.1.0/src/observe_kit/tenant.py +67 -0
  56. django_observe_kit-0.1.0/src/observe_kit/typing.py +17 -0
  57. django_observe_kit-0.1.0/src/observe_kit/urls.py +5 -0
  58. django_observe_kit-0.1.0/src/observe_kit/wagtail_integration/__init__.py +11 -0
  59. django_observe_kit-0.1.0/src/observe_kit/wagtail_integration/sentry_breadcrumbs.py +16 -0
  60. django_observe_kit-0.1.0/src/observe_kit/wagtail_integration/wagtail_hooks.py +77 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Wiphoo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,269 @@
1
+ Metadata-Version: 2.4
2
+ Name: django-observe-kit
3
+ Version: 0.1.0
4
+ Summary: Drop-in observability toolkit for Django/DRF/Wagtail
5
+ Author: Wiphoo (Terng) Methachawalit
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/wiphoo/django-observe-kit
8
+ Project-URL: Documentation, https://github.com/wiphoo/django-observe-kit/blob/main/docs/README.md
9
+ Project-URL: Repository, https://github.com/wiphoo/django-observe-kit
10
+ Project-URL: Issues, https://github.com/wiphoo/django-observe-kit/issues
11
+ Project-URL: Changelog, https://github.com/wiphoo/django-observe-kit/blob/main/CHANGELOG.md
12
+ Keywords: django,drf,wagtail,observability,opentelemetry,prometheus,sentry,tracing,metrics,logging,pii
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Environment :: Web Environment
15
+ Classifier: Framework :: Django
16
+ Classifier: Framework :: Django :: 5.2
17
+ Classifier: Framework :: Django :: 6.0
18
+ Classifier: Framework :: Django :: 6.1
19
+ Classifier: Framework :: Wagtail
20
+ Classifier: Intended Audience :: Developers
21
+ Classifier: Operating System :: OS Independent
22
+ Classifier: Programming Language :: Python :: 3
23
+ Classifier: Programming Language :: Python :: 3.10
24
+ Classifier: Programming Language :: Python :: 3.11
25
+ Classifier: Programming Language :: Python :: 3.12
26
+ Classifier: Topic :: System :: Monitoring
27
+ Classifier: Topic :: System :: Logging
28
+ Classifier: Typing :: Typed
29
+ Requires-Python: >=3.10
30
+ Description-Content-Type: text/markdown
31
+ License-File: LICENSE
32
+ Requires-Dist: Django>=5.2
33
+ Requires-Dist: djangorestframework>=3.16
34
+ Requires-Dist: prometheus-client>=0.26.0
35
+ Requires-Dist: opentelemetry-sdk>=1.38.0
36
+ Requires-Dist: opentelemetry-exporter-otlp>=1.44.0
37
+ Requires-Dist: python-json-logger>=3.0
38
+ Requires-Dist: sentry-sdk<3,>=2.66.1
39
+ Provides-Extra: wagtail
40
+ Requires-Dist: wagtail>=7.4.2; extra == "wagtail"
41
+ Dynamic: license-file
42
+
43
+ # Django Observe Kit
44
+
45
+ [![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)
46
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
47
+ [![Django 5.2+](https://img.shields.io/badge/django-5.2+-green.svg)](https://www.djangoproject.com/)
48
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/wiphoo/django-observe-kit/blob/main/LICENSE)
49
+
50
+ 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.
51
+
52
+ **Status: beta.** This is a 0.x release, and its API and defaults may change between minor versions.
53
+
54
+ ## What is not sanitized
55
+
56
+ PII scrubbing is a safety net, not a guarantee. Keep secrets and personal data out of what you log or send. In particular:
57
+
58
+ - **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).
59
+ - **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.
60
+ - **Other handlers get the original record.** This includes your own handlers and Django's `django` and `django.server` handlers.
61
+ - **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).
62
+ - **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.
63
+ - **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.
64
+ - **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.
65
+ - **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.
66
+ - **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.
67
+ - **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.
68
+ - **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.
69
+ - **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.
70
+ - **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).
71
+ - **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.
72
+
73
+ Read all [known limitations](https://github.com/wiphoo/django-observe-kit/blob/main/docs/pii.md#known-limitations) before relying on it.
74
+
75
+ ## Features
76
+
77
+ - **Request context and logging:** JSON logs with request fields, including a `request_complete` event.
78
+ - **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.
79
+ - **Metrics:** Prometheus request, latency and database metrics on `/metrics`.
80
+ - **Sentry:** error and transaction scrubbing at a configurable PII level. Sentry metrics and logs are disabled because they would bypass it.
81
+ - **DRF, audit log and Wagtail:** optional integrations.
82
+
83
+ ## Requirements
84
+
85
+ - Python 3.10 or later
86
+ - Django 5.2 or later and Django REST framework 3.16 or later (installed as a dependency)
87
+ - `sentry-sdk` 2.x only (`>=2.66.1,<3`, installed as a dependency)
88
+ - 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)
89
+
90
+ ## Installation
91
+
92
+ ```bash
93
+ pip install django-observe-kit
94
+ ```
95
+
96
+ For the Wagtail integration, install `"django-observe-kit[wagtail]"` instead.
97
+
98
+ ## Quickstart
99
+
100
+ **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.
101
+
102
+ ```python
103
+ # settings.py (append)
104
+ import os
105
+
106
+ INSTALLED_APPS += ["observe_kit"]
107
+
108
+ MIDDLEWARE += [
109
+ "observe_kit.otel.middleware.TraceContextMiddleware",
110
+ "observe_kit.logging.middleware.RequestLoggingMiddleware",
111
+ "observe_kit.metrics.middleware.PrometheusRequestMiddleware",
112
+ "observe_kit.context_middleware.RequestContextMiddleware",
113
+ "observe_kit.context_middleware.UserLoggingContextMiddleware",
114
+ "observe_kit.sentry.middleware.SentryContextMiddleware",
115
+ ]
116
+
117
+ OBSERVE_KIT = {
118
+ # Enables tracing. Traces and logs go to an OTLP/HTTP collector.
119
+ "SERVICE_NAME": "my-app",
120
+ "OTEL_ENDPOINT": "http://localhost:4318",
121
+ # Salt for hashed PII values; set a secret value per environment.
122
+ "PII_HASH_SALT": os.environ.get("PII_HASH_SALT", ""),
123
+ # /metrics is open to anyone unless you set this.
124
+ "METRICS_AUTH": "token",
125
+ "METRICS_TOKEN": os.environ.get("METRICS_TOKEN"),
126
+ }
127
+ ```
128
+
129
+ 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.
130
+
131
+ **2. Metrics URL.** Include `observe_kit.urls`, which serves `/metrics`:
132
+
133
+ ```python
134
+ # urls.py
135
+ from django.contrib import admin
136
+ from django.urls import include, path
137
+
138
+ urlpatterns = [
139
+ path("admin/", admin.site.urls),
140
+ path("", include("observe_kit.urls")),
141
+ ]
142
+ ```
143
+
144
+ **3. Run it.**
145
+
146
+ ```bash
147
+ export PII_HASH_SALT=change-me METRICS_TOKEN=change-me
148
+ python manage.py check
149
+ python manage.py runserver
150
+ ```
151
+
152
+ In another terminal:
153
+
154
+ ```bash
155
+ curl -H "Authorization: Bearer change-me" http://127.0.0.1:8000/metrics
156
+ ```
157
+
158
+ 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).
159
+
160
+ ### Manual initialisation
161
+
162
+ 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.
163
+
164
+ ```python
165
+ # mysite/apps.py
166
+ import os
167
+
168
+ from django.apps import AppConfig
169
+
170
+
171
+ class MySiteConfig(AppConfig):
172
+ name = "mysite" # your project package or one of your apps
173
+
174
+ def ready(self) -> None:
175
+ from observe_kit import configure_logging, init_sentry, init_tracing
176
+
177
+ configure_logging(level="INFO")
178
+ init_tracing(service_name="my-app", endpoint="http://localhost:4318")
179
+ if os.environ.get("SENTRY_DSN"):
180
+ init_sentry(dsn=os.environ["SENTRY_DSN"], environment="production")
181
+ ```
182
+
183
+ ```python
184
+ # manual initialisation (append to settings.py)
185
+ INSTALLED_APPS += ["mysite"]
186
+ ```
187
+
188
+ ### Exporting logs at shutdown
189
+
190
+ 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.)
191
+
192
+ - Queued records are still exported periodically.
193
+ - 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.
194
+ - 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.
195
+ - 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`.
196
+
197
+ ### `DEBUG` logging with Sentry and a failing collector
198
+
199
+ **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)`.
200
+
201
+ ## Tenant IDs
202
+
203
+ 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**:
204
+
205
+ - 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`;
206
+ - never from an IP-address host;
207
+ - 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).
208
+
209
+ 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.
210
+
211
+ ## Optional integrations
212
+
213
+ **DRF** (view-set action names on spans and routes, and an exception handler). Add to `settings.py` after the Quickstart block:
214
+
215
+ ```python
216
+ # DRF (append)
217
+ INSTALLED_APPS += ["rest_framework"]
218
+ MIDDLEWARE.insert(
219
+ MIDDLEWARE.index("observe_kit.sentry.middleware.SentryContextMiddleware"),
220
+ "observe_kit.drf.integration.DRFIntegrationMiddleware",
221
+ )
222
+ REST_FRAMEWORK = {"EXCEPTION_HANDLER": "observe_kit.drf.observed_exception_handler"}
223
+ ```
224
+
225
+ **Audit log.** Add the app, then run `python manage.py migrate`:
226
+
227
+ ```python
228
+ # audit log (append)
229
+ INSTALLED_APPS += ["observe_kit.audit"]
230
+ ```
231
+
232
+ 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:
233
+
234
+ ```python
235
+ from observe_kit.audit import audit
236
+
237
+
238
+ def approve_invoice(request, invoice):
239
+ audit(
240
+ request.user, # actor: must be logged in; pass None for an anonymous request
241
+ "invoice.approve",
242
+ obj=invoice,
243
+ extra={"reason": "monthly close"},
244
+ request=request,
245
+ )
246
+ ```
247
+
248
+ **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.)
249
+
250
+ Audit rows are protected only against [ordinary ORM calls](https://github.com/wiphoo/django-observe-kit/blob/main/docs/pii.md#audit-sink).
251
+
252
+ **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.
253
+
254
+ ## Documentation
255
+
256
+ - [Configuration reference](https://github.com/wiphoo/django-observe-kit/blob/main/docs/configuration.md)
257
+ - [Middleware reference](https://github.com/wiphoo/django-observe-kit/blob/main/docs/middleware.md)
258
+ - [PII sanitization and known limitations](https://github.com/wiphoo/django-observe-kit/blob/main/docs/pii.md)
259
+ - [HyperDX quickstart](https://github.com/wiphoo/django-observe-kit/blob/main/docs/HYPERDX_QUICKSTART.md)
260
+ - [Changelog](https://github.com/wiphoo/django-observe-kit/blob/main/CHANGELOG.md)
261
+ - [Security policy](https://github.com/wiphoo/django-observe-kit/blob/main/SECURITY.md): report vulnerabilities privately
262
+
263
+ ## Contributing
264
+
265
+ 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).
266
+
267
+ ## License
268
+
269
+ [MIT](https://github.com/wiphoo/django-observe-kit/blob/main/LICENSE)
@@ -0,0 +1,227 @@
1
+ # Django Observe Kit
2
+
3
+ [![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)
4
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
5
+ [![Django 5.2+](https://img.shields.io/badge/django-5.2+-green.svg)](https://www.djangoproject.com/)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/wiphoo/django-observe-kit/blob/main/LICENSE)
7
+
8
+ 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.
9
+
10
+ **Status: beta.** This is a 0.x release, and its API and defaults may change between minor versions.
11
+
12
+ ## What is not sanitized
13
+
14
+ PII scrubbing is a safety net, not a guarantee. Keep secrets and personal data out of what you log or send. In particular:
15
+
16
+ - **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).
17
+ - **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.
18
+ - **Other handlers get the original record.** This includes your own handlers and Django's `django` and `django.server` handlers.
19
+ - **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).
20
+ - **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.
21
+ - **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.
22
+ - **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.
23
+ - **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.
24
+ - **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.
25
+ - **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.
26
+ - **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.
27
+ - **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.
28
+ - **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).
29
+ - **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.
30
+
31
+ Read all [known limitations](https://github.com/wiphoo/django-observe-kit/blob/main/docs/pii.md#known-limitations) before relying on it.
32
+
33
+ ## Features
34
+
35
+ - **Request context and logging:** JSON logs with request fields, including a `request_complete` event.
36
+ - **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.
37
+ - **Metrics:** Prometheus request, latency and database metrics on `/metrics`.
38
+ - **Sentry:** error and transaction scrubbing at a configurable PII level. Sentry metrics and logs are disabled because they would bypass it.
39
+ - **DRF, audit log and Wagtail:** optional integrations.
40
+
41
+ ## Requirements
42
+
43
+ - Python 3.10 or later
44
+ - Django 5.2 or later and Django REST framework 3.16 or later (installed as a dependency)
45
+ - `sentry-sdk` 2.x only (`>=2.66.1,<3`, installed as a dependency)
46
+ - 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)
47
+
48
+ ## Installation
49
+
50
+ ```bash
51
+ pip install django-observe-kit
52
+ ```
53
+
54
+ For the Wagtail integration, install `"django-observe-kit[wagtail]"` instead.
55
+
56
+ ## Quickstart
57
+
58
+ **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.
59
+
60
+ ```python
61
+ # settings.py (append)
62
+ import os
63
+
64
+ INSTALLED_APPS += ["observe_kit"]
65
+
66
+ MIDDLEWARE += [
67
+ "observe_kit.otel.middleware.TraceContextMiddleware",
68
+ "observe_kit.logging.middleware.RequestLoggingMiddleware",
69
+ "observe_kit.metrics.middleware.PrometheusRequestMiddleware",
70
+ "observe_kit.context_middleware.RequestContextMiddleware",
71
+ "observe_kit.context_middleware.UserLoggingContextMiddleware",
72
+ "observe_kit.sentry.middleware.SentryContextMiddleware",
73
+ ]
74
+
75
+ OBSERVE_KIT = {
76
+ # Enables tracing. Traces and logs go to an OTLP/HTTP collector.
77
+ "SERVICE_NAME": "my-app",
78
+ "OTEL_ENDPOINT": "http://localhost:4318",
79
+ # Salt for hashed PII values; set a secret value per environment.
80
+ "PII_HASH_SALT": os.environ.get("PII_HASH_SALT", ""),
81
+ # /metrics is open to anyone unless you set this.
82
+ "METRICS_AUTH": "token",
83
+ "METRICS_TOKEN": os.environ.get("METRICS_TOKEN"),
84
+ }
85
+ ```
86
+
87
+ 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.
88
+
89
+ **2. Metrics URL.** Include `observe_kit.urls`, which serves `/metrics`:
90
+
91
+ ```python
92
+ # urls.py
93
+ from django.contrib import admin
94
+ from django.urls import include, path
95
+
96
+ urlpatterns = [
97
+ path("admin/", admin.site.urls),
98
+ path("", include("observe_kit.urls")),
99
+ ]
100
+ ```
101
+
102
+ **3. Run it.**
103
+
104
+ ```bash
105
+ export PII_HASH_SALT=change-me METRICS_TOKEN=change-me
106
+ python manage.py check
107
+ python manage.py runserver
108
+ ```
109
+
110
+ In another terminal:
111
+
112
+ ```bash
113
+ curl -H "Authorization: Bearer change-me" http://127.0.0.1:8000/metrics
114
+ ```
115
+
116
+ 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).
117
+
118
+ ### Manual initialisation
119
+
120
+ 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.
121
+
122
+ ```python
123
+ # mysite/apps.py
124
+ import os
125
+
126
+ from django.apps import AppConfig
127
+
128
+
129
+ class MySiteConfig(AppConfig):
130
+ name = "mysite" # your project package or one of your apps
131
+
132
+ def ready(self) -> None:
133
+ from observe_kit import configure_logging, init_sentry, init_tracing
134
+
135
+ configure_logging(level="INFO")
136
+ init_tracing(service_name="my-app", endpoint="http://localhost:4318")
137
+ if os.environ.get("SENTRY_DSN"):
138
+ init_sentry(dsn=os.environ["SENTRY_DSN"], environment="production")
139
+ ```
140
+
141
+ ```python
142
+ # manual initialisation (append to settings.py)
143
+ INSTALLED_APPS += ["mysite"]
144
+ ```
145
+
146
+ ### Exporting logs at shutdown
147
+
148
+ 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.)
149
+
150
+ - Queued records are still exported periodically.
151
+ - 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.
152
+ - 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.
153
+ - 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`.
154
+
155
+ ### `DEBUG` logging with Sentry and a failing collector
156
+
157
+ **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)`.
158
+
159
+ ## Tenant IDs
160
+
161
+ 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**:
162
+
163
+ - 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`;
164
+ - never from an IP-address host;
165
+ - 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).
166
+
167
+ 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.
168
+
169
+ ## Optional integrations
170
+
171
+ **DRF** (view-set action names on spans and routes, and an exception handler). Add to `settings.py` after the Quickstart block:
172
+
173
+ ```python
174
+ # DRF (append)
175
+ INSTALLED_APPS += ["rest_framework"]
176
+ MIDDLEWARE.insert(
177
+ MIDDLEWARE.index("observe_kit.sentry.middleware.SentryContextMiddleware"),
178
+ "observe_kit.drf.integration.DRFIntegrationMiddleware",
179
+ )
180
+ REST_FRAMEWORK = {"EXCEPTION_HANDLER": "observe_kit.drf.observed_exception_handler"}
181
+ ```
182
+
183
+ **Audit log.** Add the app, then run `python manage.py migrate`:
184
+
185
+ ```python
186
+ # audit log (append)
187
+ INSTALLED_APPS += ["observe_kit.audit"]
188
+ ```
189
+
190
+ 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:
191
+
192
+ ```python
193
+ from observe_kit.audit import audit
194
+
195
+
196
+ def approve_invoice(request, invoice):
197
+ audit(
198
+ request.user, # actor: must be logged in; pass None for an anonymous request
199
+ "invoice.approve",
200
+ obj=invoice,
201
+ extra={"reason": "monthly close"},
202
+ request=request,
203
+ )
204
+ ```
205
+
206
+ **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.)
207
+
208
+ Audit rows are protected only against [ordinary ORM calls](https://github.com/wiphoo/django-observe-kit/blob/main/docs/pii.md#audit-sink).
209
+
210
+ **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.
211
+
212
+ ## Documentation
213
+
214
+ - [Configuration reference](https://github.com/wiphoo/django-observe-kit/blob/main/docs/configuration.md)
215
+ - [Middleware reference](https://github.com/wiphoo/django-observe-kit/blob/main/docs/middleware.md)
216
+ - [PII sanitization and known limitations](https://github.com/wiphoo/django-observe-kit/blob/main/docs/pii.md)
217
+ - [HyperDX quickstart](https://github.com/wiphoo/django-observe-kit/blob/main/docs/HYPERDX_QUICKSTART.md)
218
+ - [Changelog](https://github.com/wiphoo/django-observe-kit/blob/main/CHANGELOG.md)
219
+ - [Security policy](https://github.com/wiphoo/django-observe-kit/blob/main/SECURITY.md): report vulnerabilities privately
220
+
221
+ ## Contributing
222
+
223
+ 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).
224
+
225
+ ## License
226
+
227
+ [MIT](https://github.com/wiphoo/django-observe-kit/blob/main/LICENSE)