diff --git a/sentry_sdk/__init__.py b/sentry_sdk/__init__.py index e149418c38..fda2f18dd1 100644 --- a/sentry_sdk/__init__.py +++ b/sentry_sdk/__init__.py @@ -37,6 +37,8 @@ "last_event_id", "new_scope", "push_scope", + "remove_attribute", + "set_attribute", "set_context", "set_extra", "set_level", diff --git a/sentry_sdk/api.py b/sentry_sdk/api.py index c4e2229938..bea22d8be7 100644 --- a/sentry_sdk/api.py +++ b/sentry_sdk/api.py @@ -70,6 +70,8 @@ def overload(x: "T") -> "T": "last_event_id", "new_scope", "push_scope", + "remove_attribute", + "set_attribute", "set_context", "set_extra", "set_level", @@ -287,6 +289,28 @@ def push_scope( # noqa: F811 return _ScopeManager() +@scopemethod +def set_attribute(attribute: str, value: "Any") -> None: + """ + Set an attribute. + + Any attributes-based telemetry (logs, metrics) captured in this scope will + include this attribute. + """ + return get_isolation_scope().set_attribute(attribute, value) + + +@scopemethod +def remove_attribute(attribute: str) -> None: + """ + Remove an attribute. + + If the attribute doesn't exist, this function will not have any effect and + it will also not raise an exception. + """ + return get_isolation_scope().remove_attribute(attribute) + + @scopemethod def set_tag(key: str, value: "Any") -> None: return get_isolation_scope().set_tag(key, value) diff --git a/tests/test_attributes.py b/tests/test_attributes.py index 40b31fa7f1..cac0a520e7 100644 --- a/tests/test_attributes.py +++ b/tests/test_attributes.py @@ -3,6 +3,27 @@ from tests.test_metrics import envelopes_to_metrics +def test_top_level_api(sentry_init, capture_envelopes): + sentry_init() + + envelopes = capture_envelopes() + + sentry_sdk.set_attribute("set", "value") + sentry_sdk.set_attribute("removed", "value") + sentry_sdk.remove_attribute("removed") + # Attempting to remove a nonexistent attribute should not raise + sentry_sdk.remove_attribute("nonexistent") + + sentry_sdk.metrics.count("test", 1) + sentry_sdk.get_client().flush() + + metrics = envelopes_to_metrics(envelopes) + (metric,) = metrics + + assert metric["attributes"]["set"] == "value" + assert "removed" not in metric["attributes"] + + def test_scope_precedence(sentry_init, capture_envelopes): # Order of precedence, from most important to least: # 1. telemetry attributes (directly supplying attributes on creation or using set_attribute)