django-observe-kit 0.1.0__py3-none-any.whl

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 (55) hide show
  1. django_observe_kit-0.1.0.dist-info/METADATA +269 -0
  2. django_observe_kit-0.1.0.dist-info/RECORD +55 -0
  3. django_observe_kit-0.1.0.dist-info/WHEEL +5 -0
  4. django_observe_kit-0.1.0.dist-info/licenses/LICENSE +21 -0
  5. django_observe_kit-0.1.0.dist-info/top_level.txt +1 -0
  6. observe_kit/__init__.py +82 -0
  7. observe_kit/apps.py +178 -0
  8. observe_kit/audit/__init__.py +25 -0
  9. observe_kit/audit/admin.py +20 -0
  10. observe_kit/audit/apps.py +16 -0
  11. observe_kit/audit/migrations/0001_initial.py +78 -0
  12. observe_kit/audit/migrations/__init__.py +0 -0
  13. observe_kit/audit/models.py +73 -0
  14. observe_kit/audit/signals.py +22 -0
  15. observe_kit/audit/utils.py +182 -0
  16. observe_kit/checks.py +35 -0
  17. observe_kit/conf.py +62 -0
  18. observe_kit/context.py +102 -0
  19. observe_kit/context_middleware.py +246 -0
  20. observe_kit/drf/__init__.py +9 -0
  21. observe_kit/drf/exception_handler.py +37 -0
  22. observe_kit/drf/integration.py +111 -0
  23. observe_kit/log_sanitize.py +430 -0
  24. observe_kit/logging/__init__.py +11 -0
  25. observe_kit/logging/config.py +159 -0
  26. observe_kit/logging/filters.py +82 -0
  27. observe_kit/logging/middleware.py +31 -0
  28. observe_kit/metrics/__init__.py +32 -0
  29. observe_kit/metrics/db.py +64 -0
  30. observe_kit/metrics/middleware.py +39 -0
  31. observe_kit/metrics/prometheus.py +263 -0
  32. observe_kit/otel/__init__.py +4 -0
  33. observe_kit/otel/config.py +403 -0
  34. observe_kit/otel/middleware.py +358 -0
  35. observe_kit/otel/sanitize.py +98 -0
  36. observe_kit/pii_rules.py +566 -0
  37. observe_kit/proxies.py +45 -0
  38. observe_kit/py.typed +0 -0
  39. observe_kit/sentry/__init__.py +4 -0
  40. observe_kit/sentry/config.py +3049 -0
  41. observe_kit/sentry/log_objects.py +238 -0
  42. observe_kit/sentry/logs.py +123 -0
  43. observe_kit/sentry/middleware.py +49 -0
  44. observe_kit/sentry/scrub/__init__.py +15 -0
  45. observe_kit/sentry/scrub/constants.py +21 -0
  46. observe_kit/sentry/scrub/decode.py +99 -0
  47. observe_kit/sentry/scrub/emails.py +248 -0
  48. observe_kit/sentry/scrub/locate.py +313 -0
  49. observe_kit/settings.py +348 -0
  50. observe_kit/tenant.py +67 -0
  51. observe_kit/typing.py +17 -0
  52. observe_kit/urls.py +5 -0
  53. observe_kit/wagtail_integration/__init__.py +11 -0
  54. observe_kit/wagtail_integration/sentry_breadcrumbs.py +16 -0
  55. observe_kit/wagtail_integration/wagtail_hooks.py +77 -0
@@ -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,55 @@
1
+ django_observe_kit-0.1.0.dist-info/licenses/LICENSE,sha256=lMoGBLMxvFpv0GmJpYIinmaGQxxiJRD-SlD5ojzFVzY,1063
2
+ observe_kit/__init__.py,sha256=Dy1I0qtRw8oqlZksV0lzCks9uSvFn9rT5I_1dB8tkQU,2904
3
+ observe_kit/apps.py,sha256=xqFBkhm3bEL7UwXgjkV2oWNPdnNtMAwK7JwBJ99-Gtc,7419
4
+ observe_kit/checks.py,sha256=M_im5Reg0aRxQLJ9Zd5YKAJdl0aGY7c7UoQ-EAnBWT8,1197
5
+ observe_kit/conf.py,sha256=uOntJMFwRh-3vqazeIRId68M_4qTvAWvSK7gXoRAO7g,2464
6
+ observe_kit/context.py,sha256=8SRm4XWXzQPBMrtTWUwjAlYz6gKg378UtriNuzLZDcw,3271
7
+ observe_kit/context_middleware.py,sha256=lE9-bW7ezYhk_0J3Q6VrFRbdRYEV8ChOWFQtwMTjGbg,9923
8
+ observe_kit/log_sanitize.py,sha256=m7DXbp7vjCb4PI_ZiWKCwnVx0d_qbcR1AQfgqEP3vW8,17551
9
+ observe_kit/pii_rules.py,sha256=jU1nN0GcsrewBVQRO1PasSkW2wtqLhK7fHutYv6COkM,22696
10
+ observe_kit/proxies.py,sha256=cG0cIgAnff0SsP7_Peo5inBWPtEGTG_wE-yG-k6dMpk,1596
11
+ observe_kit/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
+ observe_kit/settings.py,sha256=PV0WvpDQ-EoVzIH2G2b9WebjDwMmqy8EMANpv6Ez0fo,14251
13
+ observe_kit/tenant.py,sha256=caV1XZapzMjiQuz-EYInWSzgFuoc7ruVSXl7aIJiy_s,2673
14
+ observe_kit/typing.py,sha256=O-RWD7UG3oCEJFMWPH3VSZaPrQhaS6FkkUf17xLmwnM,585
15
+ observe_kit/urls.py,sha256=eN5tKf0DlTjqUX9nL5O4UpRFvKhbYILlwct_E3SDipg,121
16
+ observe_kit/audit/__init__.py,sha256=o0KmpnzUsYaUlsspQy1XsCFZT4ZpupCmKV5DEv5J8s4,760
17
+ observe_kit/audit/admin.py,sha256=GTWikRGSE5sWqtKO757GrPBglt__l7Mn8yjlS5kumls,598
18
+ observe_kit/audit/apps.py,sha256=IsJYgXpctsUHfTe_moJDw5LKDE-tx02uCaEyAfYIpEI,634
19
+ observe_kit/audit/models.py,sha256=Z6VkaNPfpCU69qace7v4uj9M_qHntGiej9d2kd3FAkU,2895
20
+ observe_kit/audit/signals.py,sha256=JDWRqx-l85Vn0OIUg3a5Rb8S8btInv09Q5P4e1xp3Gg,774
21
+ observe_kit/audit/utils.py,sha256=6yAjoiCRJLDVyrpsscw8tl650deORvdsouiZe-CxHVs,7963
22
+ observe_kit/audit/migrations/0001_initial.py,sha256=TwtQBRTENQS-1PUgXAyemHqcIEioj8nHXDpDGu5xZOg,3658
23
+ observe_kit/audit/migrations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
24
+ observe_kit/drf/__init__.py,sha256=id9tJjwuvsE84ymkSlmtik08m3Klj-JGJmlGQc7YSqg,269
25
+ observe_kit/drf/exception_handler.py,sha256=rWPEqRcuOaP14qV9MSAPQa2G1xD7cEEjNoqkFCxKycg,1090
26
+ observe_kit/drf/integration.py,sha256=Fn_YXwGaLdtug9wVR9QiCdQYyzFPcpBuJsT5bUvEbXQ,3865
27
+ observe_kit/logging/__init__.py,sha256=aQEVYs-rx6ISYqYI3truQ4r5Kwp8cC7scKy_jbOmSI4,315
28
+ observe_kit/logging/config.py,sha256=grxqJbMRAz29WSFGb3dc9ZQkhF6508EGlYMu1YV9NMA,5950
29
+ observe_kit/logging/filters.py,sha256=Hv7LKqJewUPHjRaAOcV9ANsx0Sl0ca-LjMTmLlDQRao,2384
30
+ observe_kit/logging/middleware.py,sha256=ZcVIxvbfWikzk0egAi9S48xCkTouy6_oAobAvSkwyfE,1025
31
+ observe_kit/metrics/__init__.py,sha256=aZfU20Blqppphirb4YfSDMwHzMt6y2_unKkQiKszZRg,755
32
+ observe_kit/metrics/db.py,sha256=9w804T-4n7p30M0NGrSU1Jk7nS65-5lmMZ3IRILgNxQ,1984
33
+ observe_kit/metrics/middleware.py,sha256=oJBm0vLsA0kaSylAvvAtztVcbVK7GK1RerRB0Bnjzfc,1562
34
+ observe_kit/metrics/prometheus.py,sha256=EEf7_fOCK3SQhHf5AFoy0iw6Bc7GfrnvvaVGaBbc9AU,9428
35
+ observe_kit/otel/__init__.py,sha256=XYxUGDkUE2ATegepXg5obtfePKs4R-sx9cAN2RrgbC4,186
36
+ observe_kit/otel/config.py,sha256=D22PrlJmOPkHTUKqfk-k6K4XcPXi5k6q2qD798fFprI,15829
37
+ observe_kit/otel/middleware.py,sha256=3gROTT7A83ZKGRrZ67SvuezakHpdRJNQEW3kAUC4G3o,17381
38
+ observe_kit/otel/sanitize.py,sha256=bMKEc2GvhCKIRLHJz7hnntMxpDh86uuk2ZotpOaCgzs,3684
39
+ observe_kit/sentry/__init__.py,sha256=vYma9ormo6PWWvz8vAn1D6Erwuexjd4_s2YH-r1NPeE,162
40
+ observe_kit/sentry/config.py,sha256=KonfhWq0XzAAQkqmK6jMTA1aF6s13LEd5N9jXCGARzI,146780
41
+ observe_kit/sentry/log_objects.py,sha256=eDhL6gX6vg5_NO6Po_q_RELyxtNalxrrHhVnXmee8PI,10548
42
+ observe_kit/sentry/logs.py,sha256=H3L6Ah5QkBixRImypQuRHYGRuz_Ji2RKw9BMYi7_LLY,5193
43
+ observe_kit/sentry/middleware.py,sha256=FJFd4XcehrtYO_zEoo7sdHr1TuljcA8bVQinQJM5d5E,1876
44
+ observe_kit/sentry/scrub/__init__.py,sha256=tFm9bgHCYJMfnivfFgCTfMQ7TnHBJh6EZb4E04Jt6o8,731
45
+ observe_kit/sentry/scrub/constants.py,sha256=uePUk0kUvTSbF1NGGSCzs35OZ7l7yNe6XcAshrqWWy4,763
46
+ observe_kit/sentry/scrub/decode.py,sha256=kC9r_QbZ1hksMRXX3Uw8xum1y6Ia2jtlxzcdewdSIVw,4056
47
+ observe_kit/sentry/scrub/emails.py,sha256=Igw51qZ1qsowU-UFbumHVv8zMdjWn90kxx8yBehQlfs,12638
48
+ observe_kit/sentry/scrub/locate.py,sha256=moUYKVeKEETI5WSIcGfP-zNZf8428ShemZU6H6WEkew,12085
49
+ observe_kit/wagtail_integration/__init__.py,sha256=fdbUlfBfhk2vK6v3iUqPW5jPtIQ6Okm68EtwBPwmAbo,384
50
+ observe_kit/wagtail_integration/sentry_breadcrumbs.py,sha256=CpKi-6T5UCigWYfET-e3BM5YCpD1R89HNP0wHXlBI48,456
51
+ observe_kit/wagtail_integration/wagtail_hooks.py,sha256=mdOg9gJxzXetbei51quw1w6av8OQhj1R6-MO1hQ1Mn8,3292
52
+ django_observe_kit-0.1.0.dist-info/METADATA,sha256=L4lMgyDZdSrS_KyKQ_Ykk5cMoe7OTTyighNMLs7i5bM,19359
53
+ django_observe_kit-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
54
+ django_observe_kit-0.1.0.dist-info/top_level.txt,sha256=5dojpdjrxZov3NmmUphFd7ArJ_hCfAIt5uUWj9eCKSY,12
55
+ django_observe_kit-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -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 @@
1
+ observe_kit
@@ -0,0 +1,82 @@
1
+ """Django Observe Kit
2
+ ------------------
3
+
4
+ A lightweight observability toolkit for Django, DRF, and Wagtail projects. The
5
+ library centralizes request context handling, structured logging, tracing,
6
+ metrics, and audit logging utilities so applications can adopt observability
7
+ best practices with minimal configuration.
8
+ """
9
+
10
+ from importlib.metadata import PackageNotFoundError, version
11
+
12
+ from .context import RequestContext, get_request_context, reset_request_context, set_request_context
13
+ from .context_middleware import RequestContextMiddleware, UserLoggingContextMiddleware
14
+ from .logging import (
15
+ RequestContextFilter,
16
+ RequestLoggingMiddleware,
17
+ configure_logging,
18
+ log_request_complete,
19
+ )
20
+ from .logging.config import ConfigurationError as LoggingConfigurationError
21
+ from .metrics import PrometheusRequestMiddleware, metrics_view
22
+ from .otel.config import ConfigurationError as OtelConfigurationError
23
+ from .otel.config import init_tracing
24
+ from .pii_rules import (
25
+ PiiConfig,
26
+ PiiLevel,
27
+ get_pii_config,
28
+ sanitize_headers,
29
+ sanitize_query_params,
30
+ set_pii_config,
31
+ )
32
+ from .sentry import SentryContextMiddleware, init_sentry
33
+ from .sentry.config import ConfigurationError as SentryConfigurationError
34
+ from .tenant import resolve_tenant_id
35
+
36
+ __all__ = [
37
+ "RequestContext",
38
+ "RequestContextFilter",
39
+ "RequestContextMiddleware",
40
+ "RequestLoggingMiddleware",
41
+ "PiiConfig",
42
+ "PiiLevel",
43
+ "PrometheusRequestMiddleware",
44
+ "SentryContextMiddleware",
45
+ "UserLoggingContextMiddleware",
46
+ "ConfigurationError",
47
+ "LoggingConfigurationError",
48
+ "SentryConfigurationError",
49
+ "configure_logging",
50
+ "get_pii_config",
51
+ "get_request_context",
52
+ "init_sentry",
53
+ "init_tracing",
54
+ "log_request_complete",
55
+ "metrics_view",
56
+ "reset_request_context",
57
+ "resolve_tenant_id",
58
+ "sanitize_headers",
59
+ "sanitize_query_params",
60
+ "set_pii_config",
61
+ "set_request_context",
62
+ ]
63
+
64
+ # Export ConfigurationError (all modules use the same exception class)
65
+ ConfigurationError = OtelConfigurationError
66
+
67
+ try:
68
+ # `importlib.metadata.version` resolves the *distribution* name (the PyPI
69
+ # package), not the import name. The distribution is `django-observe-kit`.
70
+ __version__ = version("django-observe-kit")
71
+ except PackageNotFoundError: # pragma: no cover - fallback when metadata missing
72
+ # Use a PEP 440 local segment so code branching on `__version__` can
73
+ # distinguish a fallback from a genuinely-tagged 0.0.0 release.
74
+ __version__ = "0.0.0+unknown"
75
+ # NB: the module-level name `logging` has been rebound to the
76
+ # `observe_kit.logging` submodule by the `from .logging import ...` above,
77
+ # so reach for the stdlib logger explicitly here.
78
+ import logging as _stdlib_logging
79
+
80
+ _stdlib_logging.getLogger(__name__).warning(
81
+ "observe_kit: package metadata not found; __version__ falls back to %s", __version__
82
+ )
observe_kit/apps.py ADDED
@@ -0,0 +1,178 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from typing import Sequence
5
+
6
+ from django.apps import AppConfig
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+ # Canonical observe_kit middleware order. Reported order for missing-required
11
+ # warnings; matches docs/HYPERDX_QUICKSTART.md and examples/*/settings.py.
12
+ _OTEL = "observe_kit.otel.middleware.TraceContextMiddleware"
13
+ _LOGGING = "observe_kit.logging.middleware.RequestLoggingMiddleware"
14
+ _METRICS = "observe_kit.metrics.middleware.PrometheusRequestMiddleware"
15
+ _CONTEXT = "observe_kit.context_middleware.RequestContextMiddleware"
16
+ _USER = "observe_kit.context_middleware.UserLoggingContextMiddleware"
17
+ _DRF = "observe_kit.drf.integration.DRFIntegrationMiddleware"
18
+ _SENTRY = "observe_kit.sentry.middleware.SentryContextMiddleware"
19
+
20
+ _CANONICAL_MIDDLEWARE_ORDER: tuple[tuple[str, bool], ...] = (
21
+ (_OTEL, True),
22
+ (_LOGGING, True),
23
+ (_METRICS, True),
24
+ (_CONTEXT, True),
25
+ (_USER, True),
26
+ (_DRF, False),
27
+ (_SENTRY, True),
28
+ )
29
+
30
+ # Behaviorally-significant ordering constraints expressed as (above, below) pairs
31
+ # in MIDDLEWARE list order. We *only* flag inversions of these pairs — pairs not
32
+ # listed (e.g. DRF↔Sentry, where DRF only does ``process_view`` and Sentry only
33
+ # ``process_request`` so their order is irrelevant) never produce warnings.
34
+ _MIDDLEWARE_ORDER_EDGES: tuple[tuple[str, str], ...] = (
35
+ (_OTEL, _LOGGING), # trace_id must be set before logging emits the record
36
+ (_OTEL, _METRICS), # trace_id must be set before metrics record the request
37
+ # process_response runs bottom-up: CONTEXT must be BELOW logging/metrics so
38
+ # its finalisation runs first, populating duration_ms/db_queries/status.
39
+ (_LOGGING, _CONTEXT),
40
+ (_METRICS, _CONTEXT),
41
+ (_CONTEXT, _USER), # USER re-binds the contextvar populated by CONTEXT
42
+ (_OTEL, _SENTRY), # Sentry scope needs trace context
43
+ (_USER, _SENTRY), # Sentry scope needs user_id
44
+ )
45
+
46
+
47
+ def _validate_middleware_order(middleware: Sequence[str]) -> list[str]:
48
+ """Return human-readable warnings for misordered observe_kit middleware.
49
+
50
+ Pure function — no Django imports, no logging. Empty list means the
51
+ observe_kit middlewares present in ``middleware`` satisfy every
52
+ declared ordering edge and no required entries are missing.
53
+
54
+ A user with no observe_kit middleware at all (programmatic usage) gets
55
+ no warnings.
56
+ """
57
+ found: dict[str, int] = {}
58
+ for idx, entry in enumerate(middleware):
59
+ # Record the first occurrence if duplicates exist.
60
+ if entry not in found:
61
+ found[entry] = idx
62
+
63
+ # Filter to observe_kit middlewares known to the canonical order.
64
+ known = {path for path, _ in _CANONICAL_MIDDLEWARE_ORDER}
65
+ present_with_idx = {path: idx for path, idx in found.items() if path in known}
66
+
67
+ if not present_with_idx:
68
+ return []
69
+
70
+ warnings: list[str] = []
71
+
72
+ # Edge check: only flag declared behaviorally-significant inversions.
73
+ for above, below in _MIDDLEWARE_ORDER_EDGES:
74
+ if above in present_with_idx and below in present_with_idx:
75
+ if present_with_idx[above] > present_with_idx[below]:
76
+ warnings.append(
77
+ f"observe_kit: MIDDLEWARE order — '{above}' "
78
+ f"(index {present_with_idx[above]}) should appear before "
79
+ f"'{below}' (index {present_with_idx[below]})."
80
+ )
81
+
82
+ # Iterate canonical order (a tuple, deterministic) for missing-required
83
+ # warnings so log output is stable across runs.
84
+ for path, required in _CANONICAL_MIDDLEWARE_ORDER:
85
+ if required and path not in present_with_idx:
86
+ warnings.append(f"observe_kit: MIDDLEWARE is missing required entry '{path}'.")
87
+
88
+ return warnings
89
+
90
+
91
+ class ObserveKitConfig(AppConfig):
92
+ default_auto_field = "django.db.models.BigAutoField"
93
+ name = "observe_kit"
94
+ verbose_name = "Observe Kit"
95
+
96
+ def ready(self) -> None:
97
+ """Auto-initialise observe_kit from the OBSERVE_KIT Django setting.
98
+
99
+ Called once after all apps are loaded. Reads
100
+ ``django.conf.settings.OBSERVE_KIT`` (optional dict) and initialises:
101
+
102
+ - JSON structured logging (always, when ENABLED is True)
103
+ - OpenTelemetry tracing + log export (when SERVICE_NAME is set)
104
+ - Sentry SDK (when SENTRY_DSN is set)
105
+
106
+ Users who prefer manual control can skip ``OBSERVE_KIT`` and call
107
+ ``configure_logging()``, ``init_tracing()``, and ``init_sentry()``
108
+ themselves — this method is a no-op when ``OBSERVE_KIT`` is absent.
109
+ """
110
+ from . import checks # noqa: F401 (registers system checks)
111
+ from .settings import get_observe_kit_settings
112
+
113
+ cfg = get_observe_kit_settings()
114
+
115
+ if not cfg.configured or not cfg.enabled:
116
+ return
117
+
118
+ # Warn about insecure configuration choices early so they surface in startup logs.
119
+ if not cfg.pii_hash_salt:
120
+ logger.warning(
121
+ "observe_kit: PII_HASH_SALT is not set. "
122
+ "Hashed PII values (IP, user-agent) are vulnerable to rainbow-table reversal. "
123
+ "Set OBSERVE_KIT['PII_HASH_SALT'] to a secret per-environment value."
124
+ )
125
+ if cfg.trusted_proxies == ["*"]:
126
+ logger.warning(
127
+ "observe_kit: TRUSTED_PROXIES is set to ['*'], which trusts any proxy for "
128
+ "X-Forwarded-For. This can allow clients to spoof their IP address. "
129
+ "Consider restricting to explicit proxy IPs in production."
130
+ )
131
+
132
+ # Validate MIDDLEWARE order (advisory; never raises).
133
+ if cfg.validate_middleware_order:
134
+ try:
135
+ from django.conf import settings as django_settings
136
+
137
+ middleware = list(getattr(django_settings, "MIDDLEWARE", []) or [])
138
+ for warning in _validate_middleware_order(middleware):
139
+ logger.warning(warning)
140
+ except Exception:
141
+ logger.exception("observe_kit: middleware-order validator failed")
142
+
143
+ # Always configure structured JSON logging.
144
+ try:
145
+ from .logging import configure_logging
146
+
147
+ configure_logging(level=cfg.log_level, pii_levels=cfg.effective_pii_levels)
148
+ except Exception:
149
+ logger.exception("observe_kit: failed to configure structured logging")
150
+
151
+ # Initialise OTEL tracing (and OTEL log export) when a service name is given.
152
+ if cfg.service_name:
153
+ try:
154
+ from .otel import init_tracing
155
+
156
+ init_tracing(
157
+ service_name=cfg.service_name,
158
+ endpoint=cfg.otel_endpoint,
159
+ sample_rate=cfg.otel_sample_rate,
160
+ )
161
+ except Exception:
162
+ logger.exception(
163
+ "observe_kit: failed to initialise OTel tracing",
164
+ extra={"service": cfg.service_name},
165
+ )
166
+
167
+ # Initialise Sentry when a DSN is provided.
168
+ if cfg.sentry_dsn:
169
+ try:
170
+ from .sentry import init_sentry
171
+
172
+ init_sentry(
173
+ dsn=cfg.sentry_dsn,
174
+ environment=cfg.sentry_environment,
175
+ traces_sample_rate=cfg.sentry_traces_sample_rate,
176
+ )
177
+ except Exception:
178
+ logger.exception("observe_kit: failed to initialise Sentry")
@@ -0,0 +1,25 @@
1
+ """Audit logging module for observe_kit.
2
+
3
+ This module provides audit logging functionality. Models are imported lazily
4
+ to avoid circular dependencies during Django setup.
5
+ """
6
+
7
+ from typing import Any
8
+
9
+ from .apps import ObserveAuditConfig
10
+ from .utils import audit
11
+
12
+ __all__ = ["AuditLog", "AuditLogImmutableError", "ObserveAuditConfig", "audit"]
13
+
14
+
15
+ def __getattr__(name: str) -> Any:
16
+ """Lazy import for models to avoid circular dependencies during Django setup."""
17
+ if name == "AuditLog":
18
+ from .models import AuditLog
19
+
20
+ return AuditLog
21
+ if name == "AuditLogImmutableError":
22
+ from .models import AuditLogImmutableError
23
+
24
+ return AuditLogImmutableError
25
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")