From 01bfc735868047956b397ac12daffa1a7e68435f Mon Sep 17 00:00:00 2001 From: immanuwell Date: Tue, 26 May 2026 08:38:23 +0400 Subject: [PATCH] fix(django): trace cache.add operations --- sentry_sdk/integrations/django/caching.py | 3 +- .../integrations/django/test_cache_module.py | 51 +++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/sentry_sdk/integrations/django/caching.py b/sentry_sdk/integrations/django/caching.py index faf1803c11..3f491fc2d0 100644 --- a/sentry_sdk/integrations/django/caching.py +++ b/sentry_sdk/integrations/django/caching.py @@ -19,6 +19,7 @@ METHODS_TO_INSTRUMENT = [ + "add", "set", "set_many", "get", @@ -52,7 +53,7 @@ def _instrument_call( address: "Optional[str]", port: "Optional[int]", ) -> "Any": - is_set_operation = method_name.startswith("set") + is_set_operation = method_name.startswith("set") or method_name == "add" is_get_method = method_name == "get" is_get_many_method = method_name == "get_many" diff --git a/tests/integrations/django/test_cache_module.py b/tests/integrations/django/test_cache_module.py index c527d24589..15274deb30 100644 --- a/tests/integrations/django/test_cache_module.py +++ b/tests/integrations/django/test_cache_module.py @@ -4,6 +4,7 @@ import pytest from django import VERSION as DJANGO_VERSION +from django.core.cache import cache from werkzeug.test import Client try: @@ -542,6 +543,56 @@ def test_cache_spans_templatetag( assert second_event["spans"][0]["data"]["cache.item_size"] == 51 +@pytest.mark.forked +@pytest.mark.parametrize("span_streaming", [True, False]) +def test_cache_spans_add( + sentry_init, + capture_events, + capture_items, + use_django_caching, + span_streaming, +): + sentry_init( + integrations=[ + DjangoIntegration( + cache_spans=True, + middleware_spans=False, + signals_spans=False, + ) + ], + traces_sample_rate=1.0, + _experiments={"trace_lifecycle": "stream" if span_streaming else "static"}, + ) + + if span_streaming: + items = capture_items("span") + + with sentry_sdk.start_transaction(name="cache-add", op="test"): + assert cache.add("cache-add-key", "value") + + sentry_sdk.flush() + spans = [item.payload for item in items if item.type == "span"] + assert len(spans) == 1 + assert spans[0]["attributes"]["sentry.op"] == "cache.put" + assert spans[0]["name"] == "cache-add-key" + assert spans[0]["attributes"]["cache.key"] == ["cache-add-key"] + assert spans[0]["attributes"]["cache.item_size"] == 5 + else: + events = capture_events() + + with sentry_sdk.start_transaction(name="cache-add", op="test"): + assert cache.add("cache-add-key", "value") + + sentry_sdk.flush() + assert len(events) == 1 + spans = events[0]["spans"] + assert len(spans) == 1 + assert spans[0]["op"] == "cache.put" + assert spans[0]["description"] == "cache-add-key" + assert spans[0]["data"]["cache.key"] == ["cache-add-key"] + assert spans[0]["data"]["cache.item_size"] == 5 + + @pytest.mark.parametrize( "method_name, args, kwargs, expected_name", [