:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(otel): name django spans by route pattern (#70674)
Paul D'Ambra181098650d64
diff --git a/posthog/otel_instrumentation.py b/posthog/otel_instrumentation.pyindex 60677fce5083..572429d953e6 100644--- a/posthog/otel_instrumentation.py+++ b/posthog/otel_instrumentation.py@@ -2,6 +2,8 @@ import osimport typingimport logging+from django.http import HttpRequest, HttpResponse+import structlogfrom opentelemetry import tracefrom opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter@@ -16,23 +18,33 @@ from opentelemetry.instrumentation.requests import RequestsInstrumentorfrom opentelemetry.sdk.resources import Resourcefrom opentelemetry.sdk.trace import TracerProviderfrom opentelemetry.sdk.trace.export import BatchSpanProcessor+from opentelemetry.trace import Span+from opentelemetry.util.http import sanitize_method# Get a structlog logger for this module's own messageslogger = structlog.get_logger(__name__)-def _otel_django_request_hook(span, request):+def _otel_django_request_hook(span: Span, request: HttpRequest) -> None:if span and span.is_recording():actual_path = request.path- http_method = request.method+ http_method = request.method or ""span.set_attribute("http.method", http_method)span.set_attribute("http.url", actual_path)# span.update_name(f"{http_method} {actual_path}") # Use with caution - high cardinality-def _otel_django_response_hook(span, request, response):- if span and span.is_recording():- span.set_attribute("http.status_code", response.status_code)+def _otel_django_response_hook(span: Span, request: HttpRequest, response: HttpResponse) -> None:+ if not span or not span.is_recording():+ return++ span.set_attribute("http.status_code", response.status_code)+ route = getattr(getattr(request, "resolver_match", None), "route", None)+ if not route:+ return++ http_method = sanitize_method((request.method or "").strip())+ span.update_name("HTTP" if http_method == "_OTHER" else f"{http_method} {route}")def initialize_otel():diff --git a/posthog/test/test_otel_instrumentation.py b/posthog/test/test_otel_instrumentation.pyindex f6ea17f8c038..dad96560d2d8 100644--- a/posthog/test/test_otel_instrumentation.py+++ b/posthog/test/test_otel_instrumentation.py@@ -2,13 +2,17 @@import osimport logging-from posthog.test.base import BaseTestfrom unittest import mock+from django.test import SimpleTestCase++from opentelemetry import trace+from parameterized import parameterized+from posthog.otel_instrumentation import _otel_django_request_hook, _otel_django_response_hook, initialize_otel-class TestOtelInstrumentation(BaseTest):+class TestOtelInstrumentation(SimpleTestCase):def setUp(self):super().setUp()# Store original levels to restore them after tests@@ -32,8 +36,6 @@ class TestOtelInstrumentation(BaseTest):# Clear any potentially set OTel provider to avoid state leakage between tests# if initialize_otel was called and set a global provider.- from opentelemetry import trace-trace._TRACER_PROVIDER = Nonesuper().tearDown()@@ -241,16 +243,30 @@ class TestOtelInstrumentation(BaseTest):mock_span.set_attribute.assert_not_called()- def test_otel_django_response_hook(self):+ @parameterized.expand([("GET", "GET api/projects/<int:team_id>/insights/"), ("CUSTOM", "HTTP")])+ def test_otel_django_response_hook(self, request_method, expected_span_name):mock_span = mock.Mock()mock_span.is_recording.return_value = True- mock_request = mock.Mock() # Not used by this hook's logic+ mock_request = mock.Mock(method=request_method)+ mock_request.resolver_match.route = "api/projects/<int:team_id>/insights/"mock_response = mock.Mock()mock_response.status_code = 200_otel_django_response_hook(mock_span, mock_request, mock_response)mock_span.set_attribute.assert_called_once_with("http.status_code", 200)+ mock_span.update_name.assert_called_once_with(expected_span_name)++ def test_otel_django_response_hook_without_resolved_route(self):+ mock_span = mock.Mock()+ mock_span.is_recording.return_value = True+ mock_request = mock.Mock(method="GET", resolver_match=object())+ mock_response = mock.Mock(status_code=404)++ _otel_django_response_hook(mock_span, mock_request, mock_response)++ mock_span.set_attribute.assert_called_once_with("http.status_code", 404)+ mock_span.update_name.assert_not_called()def test_otel_django_response_hook_not_recording(self):mock_span = mock.Mock()