The only tool you need to know what is happening and how to fix it.
Go alertingexception-trackerissue-trackinglogsmetricsmonitoringobservability-platformopen-telemetryotelsession-replaytelemetrytraces
docs: added django docs
jstojiljkovic1eca13c67ed5
diff --git a/backend/app/controllers/project.controller.go b/backend/app/controllers/project.controller.goindex 9eff298c..8e6fdae0 100644--- a/backend/app/controllers/project.controller.go+++ b/backend/app/controllers/project.controller.go@@ -41,6 +41,8 @@ var validFrameworks = map[string]bool{// PHP frameworks"symfony": true,"laravel": true,+ // Python frameworks+ "django": true,// Mobile frameworks"flutter": true,"android": true,@@ -100,7 +102,7 @@ func (p projectController) CreateProject(c *gin.Context) {if !validFrameworks[request.Framework] {traceway.CaptureMessage("Invalid framework received: " + request.Framework)- c.JSON(http.StatusBadRequest, gin.H{"error": "Framework must be one of: gin, fiber, chi, fasthttp, stdlib, custom, react, svelte, vuejs, jquery, react-native, hono, cloudflare, opentelemetry, symfony, laravel, flutter, android"})+ c.JSON(http.StatusBadRequest, gin.H{"error": "Framework must be one of: gin, fiber, chi, fasthttp, stdlib, custom, react, svelte, vuejs, jquery, react-native, hono, cloudflare, opentelemetry, symfony, laravel, django, flutter, android"})return}@@ -147,7 +149,7 @@ func (p projectController) UpdateProject(c *gin.Context) {return}if !validFrameworks[request.Framework] {- c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Framework must be one of: gin, fiber, chi, fasthttp, stdlib, custom, react, svelte, vuejs, jquery, react-native, hono, cloudflare, opentelemetry, symfony, laravel, flutter, android"})+ c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Framework must be one of: gin, fiber, chi, fasthttp, stdlib, custom, react, svelte, vuejs, jquery, react-native, hono, cloudflare, opentelemetry, symfony, laravel, django, flutter, android"})return}diff --git a/docs/components/FrameworkPicker.jsx b/docs/components/FrameworkPicker.jsxindex f5554b13..ac00bb43 100644--- a/docs/components/FrameworkPicker.jsx+++ b/docs/components/FrameworkPicker.jsx@@ -42,6 +42,14 @@ const FRAMEWORKS = [href: "/client/laravel",badge: "production",},+ {+ value: "python-django",+ label: "Django",+ description: "Django framework with OpenTelemetry auto-instrumentation.",+ icon: "/django.png",+ href: "/client/django",+ badge: "new",+ },{value: "go-gin",label: "Go Gin",diff --git a/docs/components/SdkContext.jsx b/docs/components/SdkContext.jsxindex 5f09f763..69acc0fb 100644--- a/docs/components/SdkContext.jsx+++ b/docs/components/SdkContext.jsx@@ -22,6 +22,7 @@ export const SDK_OPTIONS = [{ value: 'js-nextjs', label: 'Next.js (OTel)' },{ value: 'php-symfony', label: 'Symfony' },{ value: 'php-laravel', label: 'Laravel' },+ { value: 'python-django', label: 'Django' },{ value: 'flutter', label: 'Flutter' },{ value: 'android', label: 'Android' },{ value: 'react-native', label: 'React Native' },@@ -53,6 +54,7 @@ const PATH_SDK_MAP = {'nextjs': 'js-nextjs','symfony': 'php-symfony','laravel': 'php-laravel',+ 'django': 'python-django','flutter': 'flutter','android': 'android',}diff --git a/docs/pages/client/_meta.json b/docs/pages/client/_meta.jsonindex e4b1082e..dff8ce17 100644--- a/docs/pages/client/_meta.json+++ b/docs/pages/client/_meta.json@@ -25,6 +25,7 @@"cloudflare": "Cloudflare Workers","symfony": "Symfony","laravel": "Laravel",+ "django": "Django","flutter": "Flutter","android": "Android","react-native": "React Native"diff --git a/docs/pages/client/django/_meta.json b/docs/pages/client/django/_meta.jsonnew file mode 100644index 00000000..0aa51d6b--- /dev/null+++ b/docs/pages/client/django/_meta.json@@ -0,0 +1,8 @@+{+ "index": "Quick Start",+ "exceptions": "Exceptions",+ "spans": "Spans",+ "tasks": "Tasks",+ "metrics": "Metrics",+ "logs": "Logs"+}diff --git a/docs/pages/client/django/exceptions.mdx b/docs/pages/client/django/exceptions.mdxnew file mode 100644index 00000000..48c3fad2--- /dev/null+++ b/docs/pages/client/django/exceptions.mdx@@ -0,0 +1,174 @@+# Exceptions++`opentelemetry-instrumentation-django` records unhandled exceptions automatically. When a view raises and Django doesn't catch it before the response is sent, the middleware calls `span.record_exception(exc)` and `span.set_status(StatusCode.ERROR)` on the request span. So:++- Any exception thrown from a **view function / class-based view** is captured on the request span (which becomes a Traceway Issue).+- Any exception thrown from a **Celery task** is captured on the consumer span by `opentelemetry-instrumentation-celery` (see [Tasks](/client/django/tasks)).+- Any exception thrown inside a span you created with `tracer.start_as_current_span(...)` is captured by the context manager's `__exit__` when `set_status_on_exception=True` (the default).+- Any exception raised inside a `requests` / `httpx` / DB driver call is captured by that library's instrumentation on its own client span.++You only need the patterns on this page when:+1. You **catch** an exception and don't re-raise it, so the middleware never sees it.+2. You want to attach **extra context** (user id, request id, business attributes) to the auto-captured exception event.+3. You want a custom 500 handler to still report what failed.++## Recording an Exception on the Current Span++When you catch an error but want it reported to Traceway, record it as an event on the active span:++```python+from opentelemetry import trace+from opentelemetry.trace import Status, StatusCode+++def checkout(request):+ span = trace.get_current_span()++ try:+ payment_gateway.charge(request.user, request.POST["amount"])+ except Exception as exc:+ span.record_exception(exc)+ span.set_status(Status(StatusCode.ERROR, str(exc)))+ raise+```++`record_exception` adds an `exception` event to the span with the type, message, and traceback. Traceway extracts these events and creates Issues from them.++## Adding Attributes to Exceptions++Add context by setting span attributes before or after recording the exception:++```python+from opentelemetry import trace+from opentelemetry.trace import Status, StatusCode+++def process_order(request, order_id):+ span = trace.get_current_span()+ span.set_attribute("user.id", request.user.pk)+ span.set_attribute("order.id", order_id)++ try:+ _process_order(order_id)+ except Exception as exc:+ span.record_exception(exc, attributes={+ "order.status": "failed",+ "retry.count": int(request.headers.get("x-retry", 0)),+ })+ span.set_status(Status(StatusCode.ERROR, str(exc)))+ raise+```++The `attributes={...}` payload passed to `record_exception` is attached to the exception event itself, not the span.++## Adding Context to the Auto-Capture (Response Hook)++The Django instrumentation lets you register a `response_hook` that runs **after** middleware has populated `request.user` / `request.session`. Use it to attach request-level diagnostic fields that should appear on every span — including spans that ended with an exception event:++```python+# myproject/otel.py+from opentelemetry.instrumentation.django import DjangoInstrumentor+++def response_hook(span, request, response):+ if not span or not span.is_recording():+ return++ if hasattr(request, "user") and request.user.is_authenticated:+ span.set_attribute("enduser.id", request.user.pk)++ rid = request.headers.get("X-Request-Id")+ if rid:+ span.set_attribute("request.id", rid)+++DjangoInstrumentor().instrument(response_hook=response_hook)+```++This module must be imported before Django (top of `manage.py` / `wsgi.py` / `asgi.py`) — see the [Quick Start](/client/django#manual-initialization).++> **Why not `request_hook`?** The `request_hook` runs **before** Django's middleware chain, so `request.user` is anonymous and the resolved view name isn't on the request yet. Use `response_hook` for anything that depends on auth, sessions, or view resolution.++## Capturing Exceptions in Services++For exceptions in services that run outside a request (or are several call frames away from one), get the current span from context — it will be whatever span is active, including the Celery consumer span or a custom span you created:++```python+# myapp/services/payments.py+from opentelemetry import trace+from opentelemetry.trace import Status, StatusCode+++class PaymentService:+ def process_payment(self, customer_id: str, amount: float) -> None:+ span = trace.get_current_span()++ try:+ self.gateway.charge(customer_id, amount)+ except Exception as exc:+ span.record_exception(exc, attributes={+ "customer.id": customer_id,+ "payment.amount": amount,+ })+ span.set_status(Status(StatusCode.ERROR, str(exc)))+ raise+```++If no span is currently active (you're in a management command without a wrapping span, for example), `trace.get_current_span()` returns a no-op span — `record_exception` is silently dropped. Wrap the entry point in a span first; see [Spans](/client/django/spans) and [Tasks](/client/django/tasks#management-commands).++## Custom Exception Types++Custom exception classes work the same way — their type name appears in the Traceway dashboard:++```python+class InsufficientFundsError(RuntimeError):+ def __init__(self, account_id: str, requested: float, available: float) -> None:+ super().__init__(f"Insufficient funds: requested {requested}, available {available}")+ self.account_id = account_id+ self.requested = requested+ self.available = available+++def withdraw(request):+ span = trace.get_current_span()++ try:+ _withdraw(request)+ except InsufficientFundsError as exc:+ span.record_exception(exc, attributes={+ "account.id": exc.account_id,+ "amount.requested": exc.requested,+ "amount.available": exc.available,+ })+ span.set_status(Status(StatusCode.ERROR, str(exc)))+ raise+```++## Custom 500 Handler++If you've configured a `handler500` in `urls.py`, exceptions are already handled by Django's BaseHandler before your handler runs — the middleware has caught the exception, recorded it, and set the span status. Your `handler500` just renders the response. No extra instrumentation work is needed.++If you replace the default exception handling with custom middleware that swallows exceptions, record them on the span manually before returning a response:++```python+# myapp/middleware.py+from opentelemetry import trace+from opentelemetry.trace import Status, StatusCode+++class SwallowExceptionsMiddleware:+ def __init__(self, get_response):+ self.get_response = get_response++ def __call__(self, request):+ try:+ return self.get_response(request)+ except Exception as exc:+ span = trace.get_current_span()+ span.record_exception(exc)+ span.set_status(Status(StatusCode.ERROR, str(exc)))+ from django.http import JsonResponse+ return JsonResponse({"error": "internal"}, status=500)+```++This keeps the Issue in Traceway even though Django's response is a clean 500.diff --git a/docs/pages/client/django/index.mdx b/docs/pages/client/django/index.mdxnew file mode 100644index 00000000..4fd49a2b--- /dev/null+++ b/docs/pages/client/django/index.mdx@@ -0,0 +1,208 @@+# Django++The official [`opentelemetry-instrumentation-django`](https://github.com/open-telemetry/opentelemetry-python-contrib/tree/main/instrumentation/opentelemetry-instrumentation-django) package (from `opentelemetry-python-contrib`) automatically instruments your Django application and exports traces, metrics, and logs to Traceway's OTLP endpoints — no manual instrumentation needed.++## Prerequisites++- Python 3.9++- Django 4.x or 5.x+- pip+- A Traceway project (create one in the dashboard)++## Step 1: Install Packages++```bash+pip install \+ opentelemetry-distro \+ opentelemetry-exporter-otlp \+ opentelemetry-instrumentation-django+```++Then let the OTel bootstrapper auto-install the rest of the instrumentation that matches your installed dependencies (Postgres / MySQL / Redis / `requests` / `urllib3` / Celery / logging / …):++```bash+opentelemetry-bootstrap -a install+```++`opentelemetry-bootstrap` inspects your `site-packages` and only installs instrumentation packages that have a matching library present — re-run it whenever you add or remove dependencies.++## Step 2: Configure Environment Variables++Add the following to your `.env` (or your container / systemd unit / `manage.py` shell), replacing the endpoint and token with your project values:++```bash+OTEL_SERVICE_NAME=my-django-app+OTEL_TRACES_EXPORTER=otlp+OTEL_METRICS_EXPORTER=otlp+OTEL_LOGS_EXPORTER=otlp+OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf+OTEL_EXPORTER_OTLP_ENDPOINT=https://your-traceway-instance.com/api/otel+OTEL_EXPORTER_OTLP_HEADERS=Authorization=Bearer%20your-project-token++# Forward Python logging records (Django + your loggers) as OTel log records.+OTEL_PYTHON_LOGGING_AUTO_INSTRUMENTATION_ENABLED=true+```++Your Traceway dashboard includes a **Connection** page with a ready-made config snippet and your project token. Go to **Connection** in the sidebar to grab it.++> **Note:** `OTEL_EXPORTER_OTLP_HEADERS` is a comma-separated list of `key=value` pairs, so the `Bearer ` prefix's space must be URL-encoded as `%20`. The exporter URL-decodes header values automatically.++## Step 3: Launch Django Through the OTel Agent++Don't run `manage.py runserver` (or your WSGI/ASGI server) directly — wrap it with `opentelemetry-instrument` so the agent can patch Django, the database driver, and the HTTP client libraries before your app imports them:++```bash+# Development+opentelemetry-instrument python manage.py runserver++# Production (Gunicorn / WSGI)+opentelemetry-instrument gunicorn myproject.wsgi:application++# Production (Uvicorn / ASGI)+opentelemetry-instrument uvicorn myproject.asgi:application+```++That's it — `DjangoInstrumentor` injects its middleware at index `0` of the `MIDDLEWARE` list at startup, so every inbound HTTP request is now traced. No `settings.py` edits required.++> **Want to instrument manually instead of via the agent?** You can call `DjangoInstrumentor().instrument()` from a tiny entrypoint module (e.g. `myproject/otel.py`) that you import at the top of `manage.py` and `wsgi.py`. See [Manual Initialization](#manual-initialization) below — using `opentelemetry-instrument` is strongly preferred because it also wires up exporters and resource detection for you.++## What Gets Captured++Once configured, the Django instrumentation automatically captures:++- **Endpoints** — every HTTP request with method and route template (e.g., `GET /users/<int:id>/`), set as `http.route`+- **Status codes** — 2xx, 4xx, 5xx responses+- **Exceptions** — unhandled exceptions are recorded on the request span via `span.record_exception()` and the span is marked `ERROR`+- **Active request counter** — concurrent in-flight request count, exported as a metric+- **Duration histogram** — request latency histogram (`http.server.request.duration`)++And once `opentelemetry-bootstrap -a install` has been run, the matching auto-instrumentations also capture:++| Library | What it captures |+|---------|------------------|+| `psycopg2` / `psycopg` / `mysqlclient` / `pymysql` / `sqlite3` | Every DB query — SQL statement, duration, error |+| `redis` / `aioredis` | Redis commands (GET/SET/…) |+| `requests` / `urllib` / `urllib3` / `httpx` | Outbound HTTP — propagates W3C trace context |+| `celery` | Producer + consumer spans for queued tasks — see [Tasks](/client/django/tasks) |+| `logging` | Standard `logging` records as OTel logs (when `OTEL_PYTHON_LOGGING_AUTO_INSTRUMENTATION_ENABLED=true`) |+| `boto3` / `pika` / `kafka-python` / `pymongo` / `elasticsearch` / … | Bundled in `opentelemetry-bootstrap`'s registry; auto-installed if the library is present |++Disable any instrumentation you don't want by uninstalling its package, or by setting the matching `OTEL_PYTHON_DISABLED_INSTRUMENTATIONS` env var:++```bash+# Comma-separated entry-point names — e.g. disable Redis + outbound requests+OTEL_PYTHON_DISABLED_INSTRUMENTATIONS=redis,requests+```++## Tuning the Django Instrumentation++The middleware reads a handful of environment variables at startup:++| Variable | Default | Purpose |+|----------|---------|---------|+| `OTEL_PYTHON_DJANGO_INSTRUMENT` | `True` | Set to `False` to disable Django instrumentation while keeping the rest. |+| `OTEL_PYTHON_DJANGO_EXCLUDED_URLS` | _(unset)_ | Comma-separated regexes — matching paths are not traced. Example: `healthcheck,client/.*/info`. |+| `OTEL_PYTHON_DJANGO_TRACED_REQUEST_ATTRS` | _(unset)_ | Comma-separated `HttpRequest` attributes to attach as span attributes (e.g. `path_info,content_type`). |+| `OTEL_PYTHON_DJANGO_MIDDLEWARE_POSITION` | `0` | Index in the `MIDDLEWARE` list where the OTel middleware is inserted. |+| `OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST` | _(unset)_ | Request headers to capture (regex list). Captured as `http.request.header.<lowercased_name>`. |+| `OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE` | _(unset)_ | Response headers to capture (regex list). |+| `OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS` | _(unset)_ | Regexes of header names whose values should be redacted (e.g. `.*session.*,set-cookie`). |++## Request & Response Hooks++For attribute work that needs Django-specific context (the authenticated user, the resolved view name, the response body size), register a `response_hook` from the manual entrypoint:++```python+# myproject/otel.py+from opentelemetry.instrumentation.django import DjangoInstrumentor+++def response_hook(span, request, response):+ if not span or not span.is_recording():+ return++ if hasattr(request, "user") and request.user.is_authenticated:+ span.set_attribute("enduser.id", request.user.pk)+ span.set_attribute("enduser.role", request.user.groups.values_list("name", flat=True).first() or "")++ span.set_attribute("http.response.body.size", len(response.content) if hasattr(response, "content") else 0)+++DjangoInstrumentor().instrument(response_hook=response_hook)+```++Then import this module **before** Django is imported — typically at the very top of `manage.py` / `wsgi.py` / `asgi.py`:++```python+# manage.py+import myproject.otel # noqa: F401 — must come first++# ...standard manage.py body...+```++> **Why `response_hook` and not `request_hook`?** The `request_hook` runs **before** Django middleware, so middleware-populated attributes like `request.user` are still anonymous when it fires. Use `response_hook` for anything that depends on auth, sessions, or view resolution.++## Manual Initialization++If you can't use the `opentelemetry-instrument` agent (for example you're in a managed environment that forbids wrapping the command line), set up the SDK and instrumentation programmatically:++```python+# myproject/otel.py+from opentelemetry import trace+from opentelemetry.sdk.resources import Resource+from opentelemetry.sdk.trace import TracerProvider+from opentelemetry.sdk.trace.export import BatchSpanProcessor+from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter+from opentelemetry.instrumentation.django import DjangoInstrumentor+++resource = Resource.create({"service.name": "my-django-app"})+provider = TracerProvider(resource=resource)+provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))+trace.set_tracer_provider(provider)++DjangoInstrumentor().instrument()+```++Import this module before Django loads:++```python+# manage.py+import myproject.otel # noqa: F401+```++The `OTLPSpanExporter()` constructor reads `OTEL_EXPORTER_OTLP_ENDPOINT` / `OTEL_EXPORTER_OTLP_HEADERS` from the environment, so you still configure it the same way.++## Test Your Integration++Add a test route to verify data is flowing:++```python+# myapp/views.py+from django.http import HttpResponse+++def testing(request):+ raise RuntimeError("Test error from Traceway integration")+```++```python+# myproject/urls.py+from django.urls import path+from myapp import views++urlpatterns = [+ path("testing/", views.testing),+]+```++Visit `/testing/` in your browser, then check the Traceway dashboard — the exception should appear within a few seconds.++## Next Steps++- [Exceptions](/client/django/exceptions) — manually capture caught exceptions with context+- [Spans](/client/django/spans) — create custom spans to measure sub-operations+- [Tasks](/client/django/tasks) — trace Celery tasks and Django management commands as background tasks+- [Metrics](/client/django/metrics) — track custom counters, histograms, and gauges with the OTel Metrics API+- [Logs](/client/django/logs) — forward Django + Python `logging` records to Traceway over OTLP+- [OpenTelemetry docs](/client/otel) — how OTel traces, metrics, and logs map to Tracewaydiff --git a/docs/pages/client/django/logs.mdx b/docs/pages/client/django/logs.mdxnew file mode 100644index 00000000..d4f1475e--- /dev/null+++ b/docs/pages/client/django/logs.mdx@@ -0,0 +1,158 @@+# Logs++`opentelemetry-instrumentation-logging` (auto-installed by `opentelemetry-bootstrap`) bridges Python's standard `logging` module to the OpenTelemetry Logs SDK and OTLP exporter. Once enabled, every `logger.info(...)` / `logger.error(...)` — including records emitted by Django itself, your views, your Celery tasks, and any third-party library that uses `logging` — is forwarded to Traceway and linked to the active trace and span.++## Step 1: Enable OTLP Logs++Extend the env config from the [Quick Start](/client/django) to also turn on the logs exporter and the Python logging auto-instrumentation:++```bash+# Existing traces + metrics config from the Quick Start+OTEL_SERVICE_NAME=my-django-app+OTEL_TRACES_EXPORTER=otlp+OTEL_METRICS_EXPORTER=otlp++# Enable OTLP logs+OTEL_LOGS_EXPORTER=otlp++# Auto-forward Python `logging` records as OTel log records+OTEL_PYTHON_LOGGING_AUTO_INSTRUMENTATION_ENABLED=true++OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf+OTEL_EXPORTER_OTLP_ENDPOINT=https://your-traceway-instance.com/api/otel+OTEL_EXPORTER_OTLP_HEADERS=Authorization=Bearer%20your-project-token+```++`OTEL_EXPORTER_OTLP_ENDPOINT` is the base URL — the logs exporter appends `/v1/logs` automatically. No extra endpoint config is needed.++> **`OTEL_PYTHON_LOGGING_AUTO_INSTRUMENTATION_ENABLED` is what flips the bridge on.** Without it, the logging instrumentation only injects `trace_id` / `span_id` into your existing log formatters — your records do **not** get shipped to OTLP. The variable is read once at startup, so set it in your environment (not in a `.env` loaded after Django imports).++## Step 2: Use Python's `logging` Module as Usual++Use the standard Python logger. Because the handler runs inside the request / Celery task span, every record emitted from there carries that span's `trace_id` and `span_id` automatically:++```python+# myapp/views.py+import logging++from django.http import JsonResponse++logger = logging.getLogger(__name__)+++def create_order(request):+ order_id = "ord_123"+ logger.info("order received", extra={"order.id": order_id})++ try:+ # ... business logic ...+ logger.info("order processed", extra={"order.id": order_id})+ return JsonResponse({"status": "ok"})+ except Exception as exc:+ logger.error("order failed", extra={"order.id": order_id, "exception": str(exc)})+ raise+```++Open the endpoint's trace in the Traceway dashboard and the **Logs** tab will show these records attached. The same is true for logs emitted inside Celery tasks, management commands, and any other code that runs under an active span.++> **Attributes via `extra={...}`:** OTel's logging handler reads the `extra` dict on a `LogRecord` and attaches each key as an attribute on the OTel log record. So `logger.info("order received", extra={"order.id": "ord_123"})` produces an OTel log with attribute `order.id="ord_123"`. Use dotted keys (e.g. `order.id`, `user.id`) to match OTel semantic conventions.++## Step 3 (optional): Inject `trace_id` Into Console / File Logs++If you also write logs to the console or a file (Django's default `LOGGING` config does this in dev), the logging instrumentation injects the active `trace_id` and `span_id` into the `LogRecord` itself. Add them to your formatter to see them in your tail / Cloud Logging / wherever you read raw logs:++```python+# settings.py+LOGGING = {+ "version": 1,+ "disable_existing_loggers": False,+ "formatters": {+ "with_trace": {+ "format": "[{levelname}] {message} | trace_id={otelTraceID} span_id={otelSpanID}",+ "style": "{",+ },+ },+ "handlers": {+ "console": {+ "class": "logging.StreamHandler",+ "formatter": "with_trace",+ },+ },+ "root": {"handlers": ["console"], "level": "INFO"},+}+```++`otelTraceID` and `otelSpanID` are populated by `opentelemetry-instrumentation-logging` for every record emitted under an active span. Outside a span they are `"0"` placeholders.++> **Don't add a Python `OTLPHandler` manually.** When `OTEL_PYTHON_LOGGING_AUTO_INSTRUMENTATION_ENABLED=true`, the agent already attaches a `LoggingHandler` to the root logger. Adding another one yourself will produce duplicate log records in Traceway.++## Severity Mapping++Python's `logging` levels are mapped to OpenTelemetry severity numbers (and Traceway's TRACE → FATAL labels) as follows:++| Python Level | Numeric | OTLP Severity Number | Traceway Severity |+| ------------ | ------- | -------------------- | ----------------- |+| `DEBUG` | 10 | 5 | DEBUG |+| `INFO` | 20 | 9 | INFO |+| `WARNING` | 30 | 13 | WARN |+| `ERROR` | 40 | 17 | ERROR |+| `CRITICAL` | 50 | 21 | FATAL |++Only records at or above the root logger's configured `level` are emitted to handlers — so set `LOGGING["root"]["level"] = "INFO"` (or whatever threshold you want) to control volume.++## Logging Exceptions With Full Tracebacks++`logger.exception(...)` and `logger.error(..., exc_info=True)` both attach the traceback to the OTel log record's `exception.stacktrace` attribute, which Traceway extracts into the Logs view:++```python+import logging++logger = logging.getLogger(__name__)+++def withdraw(request):+ try:+ _withdraw(request.user, request.POST["amount"])+ except InsufficientFundsError:+ logger.exception("withdraw failed", extra={"user.id": request.user.pk})+ raise+```++Note that the *unhandled* exception is **also** captured on the request span by the Django middleware (see [Exceptions](/client/django/exceptions)). `logger.exception(...)` is for logging the same event into the Logs feed with structured attributes — not a substitute for re-raising.++## Test Your Integration++Add a route that logs at multiple levels, hit it once, and check the **Logs** page in the Traceway dashboard:++```python+# myapp/views.py+import logging++from django.http import JsonResponse++logger = logging.getLogger(__name__)+++def log_test(request):+ logger.debug("debug sample")+ logger.info("info sample", extra={"request.id": "req_1"})+ logger.warning("warning sample")+ logger.error("error sample", extra={"order.id": "ord_1"})+ return JsonResponse({"emitted": 4})+```++```python+# myproject/urls.py+urlpatterns = [+ # ...+ path("log-test/", views.log_test),+]+```++Visit `/log-test/`, then open **Logs** in the dashboard. You should see records at or above your root logger's `level` within a few seconds, each linked to the trace for that request.++## Next Steps++- [Exceptions](/client/django/exceptions) — record caught exceptions with context+- [Metrics](/client/django/metrics) — custom counters, histograms, and gauges+- [OTel Logs reference](/client/otel/logs) — full OTLP logs mapping and severity detailsdiff --git a/docs/pages/client/django/metrics.mdx b/docs/pages/client/django/metrics.mdxnew file mode 100644index 00000000..af12669b--- /dev/null+++ b/docs/pages/client/django/metrics.mdx@@ -0,0 +1,222 @@+# Metrics++The OTel auto-instrumentation captures default request, DB, and outbound-HTTP metrics automatically (e.g. `http.server.request.duration`, `http.server.active_requests`, `db.client.operation.duration`). To track custom application metrics, use the OTel Metrics API.++## Getting a Meter++Call `metrics.get_meter(__name__)` once per module — meters are cheap and cached:++```python+from opentelemetry import metrics++meter = metrics.get_meter(__name__)+```++Instruments created from the same meter + same name return the same instance, so it's safe to call `meter.create_counter("orders.created")` from multiple places.++## Supported Instruments++| Method | Use case |+|--------|----------|+| `meter.create_counter(name, unit, description)` | Monotonic counter (only goes up) |+| `meter.create_up_down_counter(...)` | Counter that can go up or down |+| `meter.create_observable_counter(...)` | Counter whose value is read via callback at export time |+| `meter.create_observable_up_down_counter(...)` | Up/down counter read via callback |+| `meter.create_gauge(...)` | Synchronous gauge — record a value at a point in time |+| `meter.create_observable_gauge(...)` | Gauge read via callback at export time |+| `meter.create_histogram(name, unit, description)` | Distribution of values (durations, sizes) |++## Counter++Counters track cumulative values that only go up (total orders, requests processed):++```python+from opentelemetry import metrics++meter = metrics.get_meter(__name__)+order_counter = meter.create_counter(+ "orders.created",+ unit="orders",+ description="Total orders created",+)++# Increment by 1+order_counter.add(1)++# Increment with attributes+order_counter.add(1, {"plan": "pro", "region": "eu"})+```++## Histogram++Histograms track distributions of values (response times, payload sizes):++```python+import time+from opentelemetry import metrics++meter = metrics.get_meter(__name__)+duration_histogram = meter.create_histogram(+ "order.processing_ms",+ unit="ms",+ description="Order processing time",+)+++def process_order(order):+ started = time.perf_counter()+ _process(order)+ duration_ms = (time.perf_counter() - started) * 1000+ duration_histogram.record(duration_ms, {"plan": order.plan})+```++Traceway converts histograms into average and count metrics (see [OTel metrics](/client/otel/metrics#histogram-handling)).++## Gauge++Gauges track point-in-time values that can go up or down (queue depth, active connections):++```python+# Synchronous — record a value when you know it+cache_size_gauge = meter.create_gauge(+ "cache.size_mb",+ unit="MB",+ description="Cache memory usage",+)+cache_size_gauge.record(42.3)+++# Observable — value is read by a callback at export time+from opentelemetry.metrics import Observation+++def queue_depth_callback(options):+ return [Observation(get_queue_size("default"))]+++meter.create_observable_gauge(+ "queue.depth",+ callbacks=[queue_depth_callback],+ unit="items",+ description="Pending jobs in the default queue",+)+```++## Batch Observation++When several observable instruments share an expensive data source, use a single callback that yields multiple `Observation`s — the source is only consulted once per export cycle:++```python+from opentelemetry.metrics import Observation+++def system_callback(options):+ usage, pressure = expensive_system_call()+ return [+ Observation(usage, {"source": "system"}),+ Observation(pressure, {"source": "system"}),+ ]+++# Register the same callback against both instruments. The OTel SDK+# de-duplicates the call internally so expensive_system_call() runs once.+meter.create_observable_counter("usage", callbacks=[system_callback], description="count of items used")+meter.create_observable_gauge("pressure", callbacks=[system_callback], description="force per unit area")+```++## Use Cases++### Business Metrics++```python+from opentelemetry import metrics++meter = metrics.get_meter(__name__)+revenue_counter = meter.create_counter("payments.revenue", unit="usd", description="Total revenue")+signups_counter = meter.create_counter("users.signups", unit="users", description="User signups")+++class PaymentService:+ def process_payment(self, order):+ self.gateway.charge(order.total)+ revenue_counter.add(order.total, {"plan": order.plan})+++def register(request):+ user = create_user(request.POST)+ signups_counter.add(1)+ return JsonResponse({"id": user.pk}, status=201)+```++### Performance Metrics++```python+import time+import requests+from opentelemetry import metrics++meter = metrics.get_meter(__name__)+external_latency = meter.create_histogram(+ "external_api.latency_ms",+ unit="ms",+ description="External API call duration",+)+++def fetch_external_data(endpoint: str) -> dict:+ started = time.perf_counter()+ try:+ return requests.get(endpoint, timeout=5).json()+ finally:+ duration_ms = (time.perf_counter() - started) * 1000+ external_latency.record(duration_ms, {"endpoint": endpoint})+```++### Resource Metrics++```python+import redis+from opentelemetry import metrics+from opentelemetry.metrics import Observation++meter = metrics.get_meter(__name__)+redis_client = redis.Redis()+++def redis_clients_callback(options):+ info = redis_client.info("clients")+ return [Observation(int(info.get("connected_clients", 0)))]+++meter.create_observable_gauge(+ "redis.connected_clients",+ callbacks=[redis_clients_callback],+ unit="connections",+ description="Active Redis connections",+)+```++## Temporality++The OTLP exporter supports a preferred temporality (`DELTA` vs `CUMULATIVE`) for exported metrics. Set it via env:++```bash+OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=DELTA+```++Leave it unset to use the SDK default.++## Metric Naming Conventions++Use dot-separated names for organization:++```python+# Good+meter.create_counter("orders.created")+meter.create_histogram("db.query_ms")+meter.create_counter("cache.hits")++# Bad+meter.create_counter("created") # too vague+meter.create_counter("orderCount") # inconsistent style+```diff --git a/docs/pages/client/django/spans.mdx b/docs/pages/client/django/spans.mdxnew file mode 100644index 00000000..5fe4b3b7--- /dev/null+++ b/docs/pages/client/django/spans.mdx@@ -0,0 +1,153 @@+# Spans++The instrumentation creates spans for HTTP requests, DB queries, Celery tasks, cache calls, and outbound HTTP automatically. To measure sub-operations like business logic, third-party API calls, or batched work, create spans using the OTel `Tracer` API.++## Getting a Tracer++Call `trace.get_tracer(__name__)` once per module — tracers are cheap, cached by name, and safe to keep at module scope:++```python+from opentelemetry import trace++tracer = trace.get_tracer(__name__)+```++The recommended pattern is `start_as_current_span` as a context manager — it activates the span, runs the block, ends the span on exit, and records any exception that propagates out:++```python+class OrderService:+ def process_order(self, order_id: int) -> None:+ with tracer.start_as_current_span("order.validate"):+ self._validate_order(order_id)++ with tracer.start_as_current_span("order.charge"):+ self._charge_payment(order_id)+```++> **Exception handling inside `start_as_current_span`:** by default, if the block raises, the span calls `record_exception(exc)` *and* `set_status(ERROR)` before re-raising — both happen automatically. This is different from some other OTel SDKs (e.g. PHP's `keepsuit/laravel-opentelemetry::measure`) which only call `record_exception` and leave the status unset. If you want to suppress the auto-status (for example you're treating a `Http404` as a normal outcome, not an error), pass `set_status_on_exception=False`:+>+> ```python+> with tracer.start_as_current_span("lookup-user", set_status_on_exception=False) as span:+> try:+> return User.objects.get(pk=user_id)+> except User.DoesNotExist:+> span.set_attribute("user.found", False)+> return None+> ```++### With Attributes++Set attributes on the span via the context manager's binding, or via `trace.get_current_span()` from anywhere inside the block:++```python+with tracer.start_as_current_span("stripe.charge") as span:+ span.set_attribute("payment.amount", amount)+ span.set_attribute("payment.currency", "usd")+ return stripe.charge(amount)+```++To set initial attributes when the span is created (useful when sampling decisions depend on them), pass them through `attributes=`:++```python+with tracer.start_as_current_span(+ "stripe.charge",+ attributes={"payment.amount": amount, "payment.currency": "usd"},+):+ return stripe.charge(amount)+```++### Nested Spans++Child spans opened with `start_as_current_span` are automatically activated, so any further spans nest under them:++```python+with tracer.start_as_current_span("order.fulfill"):+ with tracer.start_as_current_span("inventory.reserve"):+ reserve()+ with tracer.start_as_current_span("payment.charge"):+ charge()+ with tracer.start_as_current_span("email.send"):+ notify()+```++## Manual Span Management++If you need finer control (e.g., spans that cross function boundaries or that need to outlive a `with` block), open the span manually and activate it with `trace.use_span` for the lifetime of the work:++```python+from opentelemetry import trace++tracer = trace.get_tracer(__name__)++span = tracer.start_span("long-running-job")+with trace.use_span(span, end_on_exit=True):+ do_work()+```++Setting `end_on_exit=True` makes `use_span` close the span when the block exits. Always pair `start_span` with either `use_span(..., end_on_exit=True)` or an explicit `span.end()` in a `finally` block — otherwise the span leaks and is never exported.++## Other Tracer Utilities++A handful of helpers on the OTel API surface come in handy when working with custom spans:++```python+from opentelemetry import trace+from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator++trace.get_current_span() # the currently active Span+trace.get_current_span().get_span_context() # SpanContext (trace_id, span_id, flags)+format(trace.get_current_span().get_span_context().trace_id, "032x") # trace id as hex string++# Inject the active trace context into outbound headers — most users don't need this,+# because requests/httpx/urllib3 instrumentation already injects W3C headers automatically.+carrier: dict[str, str] = {}+TraceContextTextMapPropagator().inject(carrier)+# carrier now contains "traceparent" (and "tracestate" if set)+```++## Adding Attributes++Attach metadata to spans for filtering and debugging:++```python+with tracer.start_as_current_span("db-query") as span:+ span.set_attribute("db.system", "postgresql")+ span.set_attribute("db.statement", "SELECT * FROM users WHERE id = $1")+ rows = run_query()+ span.set_attribute("db.row_count", len(rows))+```++For DB queries you go through Django's ORM, you don't need to do this — `opentelemetry-instrumentation-psycopg2` (or your DB driver's matching instrumentation) sets `db.system` / `db.statement` automatically.++## Recording Errors on Spans++When a span's operation fails and you don't want to rely on the auto-record behavior (for example you catch the error, downgrade it to a warning, and don't re-raise), record the exception and set the status explicitly:++```python+import requests+from opentelemetry import trace+from opentelemetry.trace import Status, StatusCode++tracer = trace.get_tracer(__name__)++with tracer.start_as_current_span("external-api-call") as span:+ try:+ response = requests.get("https://api.example.com/data", timeout=5)+ response.raise_for_status()+ except requests.RequestException as exc:+ span.record_exception(exc)+ span.set_status(Status(StatusCode.ERROR, str(exc)))+ raise+```++## Span Naming Conventions++Use descriptive names that indicate the operation type:++| Good | Bad |+|------|-----|+| `db.users.find` | `query` |+| `cache.sessions.get` | `cache` |+| `stripe.charge` | `api` |+| `s3.upload-image` | `upload` |+| `email.send-welcome` | `send` |diff --git a/docs/pages/client/django/tasks.mdx b/docs/pages/client/django/tasks.mdxnew file mode 100644index 00000000..62724170--- /dev/null+++ b/docs/pages/client/django/tasks.mdx@@ -0,0 +1,146 @@+# Tasks++Django itself doesn't ship a built-in task queue, so most Django apps use **Celery**. The official [`opentelemetry-instrumentation-celery`](https://github.com/open-telemetry/opentelemetry-python-contrib/tree/main/instrumentation/opentelemetry-instrumentation-celery) package auto-traces Celery: when a task is dispatched, a `PRODUCER` span is created; when the worker picks it up, a `CONSUMER` span runs the handler. W3C trace context is propagated through the task headers so the consumer span links back to the dispatch trace — the full lifecycle is visible as one continuous trace in Traceway, and each consumed task appears as a **task** with duration, status, and any child spans.++This page covers Celery (the typical setup) and Django management commands. Other Django task systems (RQ, Huey, Django-Q, Dramatiq) follow the same OTel idioms — wrap the handler in `tracer.start_as_current_span(...)` and you get the same Traceway view.++## Celery Setup++`opentelemetry-bootstrap -a install` already installed `opentelemetry-instrumentation-celery` for you when you followed the [Quick Start](/client/django). If you skipped that step:++```bash+pip install opentelemetry-instrumentation-celery+```++The Celery instrumentation hooks signal handlers via Celery's own signal API — it does **not** auto-activate from `opentelemetry-instrument` alone in every layout. Make sure it's invoked once, before workers start consuming, by adding it to the OTel entrypoint module you already import from `manage.py` / `wsgi.py`:++```python+# myproject/otel.py+from opentelemetry.instrumentation.django import DjangoInstrumentor+from opentelemetry.instrumentation.celery import CeleryInstrumentor++DjangoInstrumentor().instrument()+CeleryInstrumentor().instrument()+```++For the worker process, launch it the same way as the web server — wrap it with the agent so the SDK + exporters are configured:++```bash+opentelemetry-instrument celery -A myproject worker -l info+opentelemetry-instrument celery -A myproject beat -l info+```++That's it — every Celery task is now traced. The same setup applies whether you use `redis`, `rabbitmq`, `sqs`, or `database` brokers.++## What Gets Captured++For each Celery task the instrumentation creates two spans:++- **Publish span** — name `apply_async/<task-name>`, `PRODUCER` kind, ended when Celery finishes pushing the payload to the broker.+- **Run span** — name `run/<task-name>`, `CONSUMER` kind, ended when the handler returns or fails. On a task failure the span records the exception and is marked `STATUS_ERROR`.++Both spans carry these attributes (using OTel messaging semantic conventions):++| Attribute | Value |+|---|---|+| `messaging.system` | `celery` |+| `messaging.destination` | The queue name (e.g. `celery`, `priority-high`) |+| `messaging.message_id` | Celery's task UUID |+| `messaging.conversation_id` | Celery's `root_id` (for chained tasks) |+| `celery.task_name` | Fully-qualified task name (e.g. `myapp.tasks.send_welcome_email`) |+| `celery.action` | `apply_async` (producer) or `run` (consumer) |+| `celery.state` | Task state on completion — `SUCCESS`, `FAILURE`, `RETRY` |++W3C trace context is also injected into the task headers, so the run span is linked to the trace where the task was originally dispatched — even if dispatch and execution happen on different services. Any spans you create inside the task body automatically nest under the run span.++## Adding Attributes in Tasks++Since the instrumentation activates the consumer span before your task body runs, use `trace.get_current_span()` to add custom attributes:++```python+# myapp/tasks.py+from celery import shared_task+from opentelemetry import trace+++@shared_task+def send_order_email(order_id: int, recipient: str) -> None:+ span = trace.get_current_span()+ span.set_attribute("order.id", order_id)+ span.set_attribute("email.to", recipient)++ # ... business logic ...+```++## Child Spans in Tasks++For tasks with distinct sub-operations, use the `Tracer` API to create child spans. They automatically nest under the task's run span:++```python+# myapp/tasks.py+from celery import shared_task+from opentelemetry import trace++tracer = trace.get_tracer(__name__)+++@shared_task+def process_payment(payment_id: int, amount: float) -> None:+ with tracer.start_as_current_span("validate.payment") as span:+ span.set_attribute("payment.id", payment_id)+ _validate(payment_id)++ with tracer.start_as_current_span("charge.gateway") as span:+ span.set_attribute("payment.amount", amount)+ _charge_gateway(payment_id, amount)+```++## Periodic Tasks (Celery Beat)++Tasks scheduled by Celery Beat run through the same code path as `apply_async`, so they get the same producer + consumer span pair automatically. The producer span is opened by Beat when it dispatches the schedule entry; the consumer span is opened by whichever worker picks the task up.++If you want to attribute beat-dispatched tasks differently in the dashboard, set an attribute on the consumer side:++```python+@shared_task(bind=True)+def nightly_cleanup(self) -> None:+ span = trace.get_current_span()+ span.set_attribute("celery.scheduled_by", "beat")++ # ... work ...+```++## Management Commands++Django management commands run outside the HTTP request cycle, so the Django middleware never opens a root span for them. Unlike Celery tasks, management commands are **not traced automatically** — wrap the command body in a span yourself:++```python+# myapp/management/commands/cleanup_orphans.py+from django.core.management.base import BaseCommand+from opentelemetry import trace++tracer = trace.get_tracer(__name__)+++class Command(BaseCommand):+ help = "Delete orphaned rows that have no foreign key parent."++ def add_arguments(self, parser):+ parser.add_argument("--dry-run", action="store_true")++ def handle(self, *args, **options):+ with tracer.start_as_current_span("cleanup.orphans") as span:+ span.set_attribute("cleanup.dry_run", bool(options["dry_run"]))++ # ... do work ...+```++Each wrapped command opens as a root span on entry and ends on exit. Inside the block, `trace.get_current_span()` returns the active span and any further spans (DB queries, outbound HTTP) nest under it.++Run the command via the OTel agent so the SDK + exporters are configured exactly like the web process:++```bash+opentelemetry-instrument python manage.py cleanup_orphans+```++If you skip the wrapping span, the command's DB queries and HTTP calls still produce spans — but each one is a disconnected root span in Traceway. The wrapping span is what ties them into a single task you can filter on.diff --git a/docs/pages/client/otel/index.mdx b/docs/pages/client/otel/index.mdxindex 1f3de17d..a13a7320 100644--- a/docs/pages/client/otel/index.mdx+++ b/docs/pages/client/otel/index.mdx@@ -18,6 +18,7 @@ Any language with an OTel SDK can export to Traceway. Here are the most common o|----------|----------|---------|| Java | [opentelemetry-java](https://github.com/open-telemetry/opentelemetry-java) | [Agent JAR](https://opentelemetry.io/docs/zero-code/java/agent/) || Python | [opentelemetry-python](https://github.com/open-telemetry/opentelemetry-python) | `pip install opentelemetry-sdk` |+| Python / Django | [opentelemetry-python-contrib](https://github.com/open-telemetry/opentelemetry-python-contrib) | `pip install opentelemetry-distro opentelemetry-exporter-otlp opentelemetry-instrumentation-django` — see [Django guide](/client/django) || C# / .NET | [opentelemetry-dotnet](https://github.com/open-telemetry/opentelemetry-dotnet) | `dotnet add package OpenTelemetry` || Go | [opentelemetry-go](https://github.com/open-telemetry/opentelemetry-go) | `go get go.opentelemetry.io/otel` || Node.js | [opentelemetry-js](https://github.com/open-telemetry/opentelemetry-js) | `npm install @opentelemetry/sdk-node` — see [Node.js guide](/client/node-sdk), [NestJS guide](/client/nestjs), [Hono guide](/client/hono), [Next.js guide](/client/nextjs) |diff --git a/docs/public/django.png b/docs/public/django.pngnew file mode 100644index 00000000..2a1d873eBinary files /dev/null and b/docs/public/django.png differdiff --git a/frontend/src/lib/components/framework-combobox.svelte b/frontend/src/lib/components/framework-combobox.svelteindex 1255ecdc..79626a40 100644--- a/frontend/src/lib/components/framework-combobox.svelte+++ b/frontend/src/lib/components/framework-combobox.svelte@@ -34,6 +34,7 @@{ value: 'jquery', label: 'jQuery', description: 'Legacy-friendly AJAX and DOM library', group: 'JavaScript' },{ value: 'symfony', label: 'Symfony', description: 'PHP full-stack framework (OTLP)', group: 'PHP' },{ value: 'laravel', label: 'Laravel', description: 'PHP full-stack framework (OTLP)', group: 'PHP' },+ { value: 'django', label: 'Django', description: 'Python full-stack framework (OTLP)', group: 'Python' },{ value: 'hono', label: 'Hono', description: 'Lightweight multi-runtime framework (OTLP)', group: 'Backend' },{ value: 'cloudflare', label: 'Cloudflare', description: 'Cloudflare Workers (OTLP Traces)', group: 'Backend' },{ value: 'opentelemetry', label: 'OpenTelemetry', description: 'Vendor-neutral observability', group: 'Backend' },@@ -58,6 +59,7 @@const goFrameworks = $derived(filteredFrameworks.filter(f => f.group === 'Go'));const jsFrameworks = $derived(filteredFrameworks.filter(f => f.group === 'JavaScript'));const phpFrameworks = $derived(filteredFrameworks.filter(f => f.group === 'PHP'));+ const pythonFrameworks = $derived(filteredFrameworks.filter(f => f.group === 'Python'));const backendFrameworks = $derived(filteredFrameworks.filter(f => f.group === 'Backend'));const mobileFrameworks = $derived(filteredFrameworks.filter(f => f.group === 'Mobile'));@@ -203,6 +205,32 @@{/each}</Combobox.Group>{/if}+ {#if pythonFrameworks.length > 0}+ <Combobox.Group>+ <Combobox.GroupHeading class="px-2 py-1.5 text-xs font-semibold text-muted-foreground">Python</Combobox.GroupHeading>+ {#each pythonFrameworks as fw}+ <Combobox.Item+ value={fw.value}+ class={cn(+ "data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 ps-2 pe-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"+ )}+ >+ {#snippet children({ selected })}+ <div class="flex items-center gap-2">+ <FrameworkIcon framework={fw.value} />+ <div class="flex flex-col">+ <span class="font-medium">{fw.label}</span>+ <span class="text-xs text-muted-foreground">{fw.description}</span>+ </div>+ </div>+ {#if selected}+ <Check class="absolute end-2 size-4" />+ {/if}+ {/snippet}+ </Combobox.Item>+ {/each}+ </Combobox.Group>+ {/if}{#if backendFrameworks.length > 0}<Combobox.Group><Combobox.GroupHeading class="px-2 py-1.5 text-xs font-semibold text-muted-foreground">Backend</Combobox.GroupHeading>diff --git a/frontend/src/lib/components/framework-icon.svelte b/frontend/src/lib/components/framework-icon.svelteindex 29c3c19b..933a09cb 100644--- a/frontend/src/lib/components/framework-icon.svelte+++ b/frontend/src/lib/components/framework-icon.svelte@@ -58,6 +58,8 @@<img src="/symfony.png" alt="Symfony" class={className} />{:else if framework === 'laravel'}<img src="/laravel.png" alt="Laravel" class={className} />+{:else if framework === 'django'}+ <img src="/django.png" alt="Django" class={className} style="object-fit: contain;" />{:else if framework === 'flutter'}<img src="/flutter.png" alt="Flutter" class={className} style="object-fit: contain;" />{:else if framework === 'android'}diff --git a/frontend/src/lib/state/projects.svelte.ts b/frontend/src/lib/state/projects.svelte.tsindex 32bdf0e8..c346eec6 100644--- a/frontend/src/lib/state/projects.svelte.ts+++ b/frontend/src/lib/state/projects.svelte.ts@@ -1,7 +1,7 @@import { api } from '$lib/api';import { authState } from './auth.svelte';-export type Framework = 'gin' | 'fiber' | 'chi' | 'fasthttp' | 'stdlib' | 'custom' | 'react' | 'svelte' | 'vuejs' | 'nextjs' | 'nestjs' | 'express' | 'remix' | 'jquery' | 'react-native' | 'hono' | 'cloudflare' | 'opentelemetry' | 'symfony' | 'laravel' | 'flutter' | 'android';+export type Framework = 'gin' | 'fiber' | 'chi' | 'fasthttp' | 'stdlib' | 'custom' | 'react' | 'svelte' | 'vuejs' | 'nextjs' | 'nestjs' | 'express' | 'remix' | 'jquery' | 'react-native' | 'hono' | 'cloudflare' | 'opentelemetry' | 'symfony' | 'laravel' | 'django' | 'flutter' | 'android';export const FRONTEND_FRAMEWORKS: Framework[] = ['react', 'svelte', 'vuejs', 'jquery', 'react-native', 'flutter', 'android'];export const JS_FRAMEWORKS: Framework[] = ['react', 'svelte', 'vuejs', 'nextjs', 'nestjs', 'express', 'remix', 'jquery', 'react-native'];@@ -27,6 +27,7 @@ export const FRAMEWORK_LABELS: Record<Framework, string> = {opentelemetry: 'OpenTelemetry',symfony: 'Symfony',laravel: 'Laravel',+ django: 'Django',flutter: 'Flutter',android: 'Android',};diff --git a/frontend/src/lib/utils/framework-code.ts b/frontend/src/lib/utils/framework-code.tsindex 2b54159a..842828c1 100644--- a/frontend/src/lib/utils/framework-code.ts+++ b/frontend/src/lib/utils/framework-code.ts@@ -38,6 +38,8 @@ export function getInstallCommand(framework: Framework): string {return 'composer require traceway/opentelemetry-symfony open-telemetry/exporter-otlp php-http/guzzle7-adapter';case 'laravel':return 'composer require keepsuit/laravel-opentelemetry open-telemetry/exporter-otlp php-http/guzzle7-adapter';+ case 'django':+ return 'pip install opentelemetry-distro opentelemetry-exporter-otlp opentelemetry-instrumentation-django && opentelemetry-bootstrap -a install';case 'cloudflare':return '';case 'opentelemetry':@@ -339,6 +341,28 @@ $kernel->terminate($request, $response);`;// traced automatically. Open config/opentelemetry.php to tune which// instrumentations are enabled.`;+ case 'django':+ return `# .env — point the OTLP exporter at Traceway+#+# OTEL_SERVICE_NAME=my-django-app+# OTEL_TRACES_EXPORTER=otlp+# OTEL_METRICS_EXPORTER=otlp+# OTEL_LOGS_EXPORTER=otlp+# OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf+# OTEL_EXPORTER_OTLP_ENDPOINT=${backendUrl}/api/otel+# OTEL_EXPORTER_OTLP_HEADERS=Authorization=Bearer%20${token || 'YOUR_TOKEN'}+# OTEL_PYTHON_LOGGING_AUTO_INSTRUMENTATION_ENABLED=true++# Then launch Django through the OTel agent — no code changes needed:+#+# opentelemetry-instrument python manage.py runserver+# opentelemetry-instrument gunicorn myproject.wsgi:application+#+# DjangoInstrumentor auto-installs middleware at index 0 and traces every+# inbound request. opentelemetry-bootstrap also wired psycopg/redis/requests/+# celery/logging instrumentation, so DB queries, cache ops, outbound HTTP+# and queued tasks are traced automatically.`;+case 'hono':return '';@@ -423,6 +447,23 @@ use Illuminate\\Support\\Facades\\Route;Route::get('/testing', function () {throw new \\RuntimeException('Test error from Traceway integration');});`;+ }+ if (framework === 'django') {+ return `# myapp/views.py+from django.http import HttpResponse+++def testing(request):+ raise RuntimeError("Test error from Traceway integration")+++# myproject/urls.py+from django.urls import path+from myapp import views++urlpatterns = [+ path("testing/", views.testing),+]`;}if (framework === 'flutter') {return `// Trigger a test error@@ -448,6 +489,9 @@ export function getTestingRouteCode2(framework?: Framework): string {if (framework === 'laravel') {return '';}+ if (framework === 'django') {+ return '';+ }if (framework === 'flutter') {return `import 'package:traceway/traceway.dart';@@ -548,15 +592,17 @@ export function getFrameworkLabel(framework: Framework): string {opentelemetry: 'OpenTelemetry',symfony: 'Symfony',laravel: 'Laravel',+ django: 'Django',flutter: 'Flutter',android: 'Android',};return labels[framework] || framework;}-export function getCodeLanguage(framework: Framework): 'go' | 'javascript' | 'bash' | 'php' {+export function getCodeLanguage(framework: Framework): 'go' | 'javascript' | 'bash' | 'php' | 'python' {if (framework === 'symfony') return 'php';if (framework === 'laravel') return 'php';+ if (framework === 'django') return 'python';if (framework === 'opentelemetry') return 'go';if (framework === 'hono') return 'javascript';if (framework === 'cloudflare') return 'javascript';diff --git a/frontend/src/routes/+page.svelte b/frontend/src/routes/+page.svelteindex cb378913..39047a0d 100644--- a/frontend/src/routes/+page.svelte+++ b/frontend/src/routes/+page.svelte@@ -40,6 +40,7 @@import javascript from 'svelte-highlight/languages/javascript';import bash from 'svelte-highlight/languages/bash';import php from 'svelte-highlight/languages/php';+ import python from 'svelte-highlight/languages/python';import { themeState } from '$lib/state/theme.svelte';import yaml from 'svelte-highlight/languages/yaml';import 'svelte-highlight/styles/github-dark.css';@@ -142,7 +143,7 @@projectWithToken ? getCodeLanguage(projectWithToken.framework) : ('go' as const));- const highlightLanguage = $derived(codeLanguage === 'javascript' ? javascript : codeLanguage === 'php' ? php : codeLanguage === 'bash' ? bash : go);+ const highlightLanguage = $derived(codeLanguage === 'javascript' ? javascript : codeLanguage === 'php' ? php : codeLanguage === 'python' ? python : codeLanguage === 'bash' ? bash : go);const testingRouteCode = $derived(getTestingRouteCode(projectWithToken?.framework));const testingRouteCode2 = $derived(getTestingRouteCode2(projectWithToken?.framework));diff --git a/frontend/src/routes/connection/+page.svelte b/frontend/src/routes/connection/+page.svelteindex 53a3b37d..79eefe6b 100644--- a/frontend/src/routes/connection/+page.svelte+++ b/frontend/src/routes/connection/+page.svelte@@ -23,6 +23,7 @@import javascript from 'svelte-highlight/languages/javascript';import bash from 'svelte-highlight/languages/bash';import php from 'svelte-highlight/languages/php';+ import python from 'svelte-highlight/languages/python';import yaml from 'svelte-highlight/languages/yaml';import { themeState } from '$lib/state/theme.svelte';import 'svelte-highlight/styles/github-dark.css';@@ -109,6 +110,7 @@ service:if (!projectWithToken) return go;if (projectWithToken.framework === 'symfony') return php;if (projectWithToken.framework === 'laravel') return php;+ if (projectWithToken.framework === 'django') return python;if (isJsFramework(projectWithToken.framework)) return javascript;return go;});@@ -415,7 +417,7 @@ service:<CardHeader><CardTitle>Installation</CardTitle><CardDescription- >Install the required packages{isJs ? '' : projectWithToken?.framework === 'symfony' || projectWithToken?.framework === 'laravel' ? ' using composer' : ' using go get'}.</CardDescription+ >Install the required packages{isJs ? '' : projectWithToken?.framework === 'symfony' || projectWithToken?.framework === 'laravel' ? ' using composer' : projectWithToken?.framework === 'django' ? ' using pip' : ' using go get'}.</CardDescription></CardHeader><CardContent>diff --git a/frontend/static/django.png b/frontend/static/django.pngnew file mode 100644index 00000000..2a1d873eBinary files /dev/null and b/frontend/static/django.png differ