Skip to content

Commit 8254ece

Browse files
committed
fix(django): avoid empty span name on empty path
when using `path('',...)`, previous code produces spans with an empty string name. This change corrects this fallback behavior and adds a test.
1 parent 890e5dd commit 8254ece

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

instrumentation/opentelemetry-instrumentation-django/src/opentelemetry/instrumentation/django/middleware/otel_middleware.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@ def _get_span_name(request):
172172
else:
173173
match = resolve(request.path)
174174

175-
if hasattr(match, "route"):
175+
if hasattr(match, "route") and match.route:
176176
return match.route
177177

178178
# Instead of using `view_name`, better to use `_func_name` as some applications can use similar

instrumentation/opentelemetry-instrumentation-django/tests/test_middleware.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@
7575

7676
if DJANGO_2_0:
7777
from django.urls import re_path
78+
from django.urls import path
7879
else:
7980
from django.conf.urls import url as re_path
8081

@@ -87,6 +88,7 @@
8788
re_path(r"^excluded_noarg/", excluded_noarg),
8889
re_path(r"^excluded_noarg2/", excluded_noarg2),
8990
re_path(r"^span_name/([0-9]{4})/$", route_span_name),
91+
path("", traced, name="empty"),
9092
]
9193
_django_instrumentor = DjangoInstrumentor()
9294

@@ -207,6 +209,18 @@ def test_not_recording(self):
207209
self.assertFalse(mock_span.set_attribute.called)
208210
self.assertFalse(mock_span.set_status.called)
209211

212+
def test_empty_path(self):
213+
Client().get("/")
214+
215+
spans = self.memory_exporter.get_finished_spans()
216+
self.assertEqual(len(spans), 1)
217+
218+
span = spans[0]
219+
220+
self.assertEqual(
221+
span.name, "empty"
222+
)
223+
210224
def test_traced_post(self):
211225
Client().post("/traced/")
212226

0 commit comments

Comments
 (0)