|
7 | 7 | from opentelemetry.sdk.trace import SpanProcessor, ReadableSpan |
8 | 8 | from opentelemetry.trace import Span |
9 | 9 |
|
| 10 | +from sap_cloud_sdk.core.runtime_context import APP_TENANT_ID, GLOBAL_TENANT_ID, USER_ID |
10 | 11 | from sap_cloud_sdk.core.telemetry.constants import ( |
11 | 12 | ATTR_SAP_TENANT_ID, |
12 | 13 | ATTR_USER_ID, |
13 | 14 | ) |
14 | 15 |
|
15 | 16 | logger = logging.getLogger(__name__) |
16 | 17 |
|
| 18 | +_CONTEXT_TO_SPAN_ATTR = { |
| 19 | + APP_TENANT_ID: ATTR_SAP_TENANT_ID, |
| 20 | + GLOBAL_TENANT_ID: ATTR_SAP_TENANT_ID, |
| 21 | + USER_ID: ATTR_USER_ID, |
| 22 | +} |
| 23 | + |
17 | 24 |
|
18 | 25 | class RuntimeContextSpanProcessor(SpanProcessor): |
19 | 26 | """Injects tenant and user identity from the SDK runtime context into every span. |
20 | 27 |
|
21 | | - Reads TENANT_ID, GLOBAL_TENANT_ID, and USER_ID from the runtime context populated |
22 | | - by bootstrap() providers (e.g. IASContextProvider) and stamps them as span attributes |
23 | | - on every span at start time. |
| 28 | + Reads APP_TENANT_ID, GLOBAL_TENANT_ID, and USER_ID from the runtime context |
| 29 | + populated by bootstrap() providers (e.g. IASContextProvider) and stamps them |
| 30 | + as span attributes on every span at start time. |
24 | 31 | """ |
25 | 32 |
|
26 | 33 | def on_start(self, span: Span, parent_context: Optional[Context] = None) -> None: |
27 | 34 | if not span.is_recording(): |
28 | 35 | return |
29 | 36 | try: |
30 | | - from sap_cloud_sdk.core.runtime_context import ( |
31 | | - get_context, |
32 | | - APP_TENANT_ID, |
33 | | - GLOBAL_TENANT_ID, |
34 | | - USER_ID, |
35 | | - ) |
| 37 | + from sap_cloud_sdk.core.runtime_context import get_context |
36 | 38 |
|
37 | 39 | ctx = get_context() |
38 | | - if app_tenant_id := ctx.get(APP_TENANT_ID): |
39 | | - span.set_attribute(ATTR_SAP_TENANT_ID, app_tenant_id) |
40 | | - if global_tenant_id := ctx.get(GLOBAL_TENANT_ID): |
41 | | - span.set_attribute(ATTR_SAP_TENANT_ID, global_tenant_id) |
42 | | - if user_id := ctx.get(USER_ID): |
43 | | - span.set_attribute(ATTR_USER_ID, user_id) |
| 40 | + for context_key, span_attr in _CONTEXT_TO_SPAN_ATTR.items(): |
| 41 | + if value := ctx.get(context_key): |
| 42 | + span.set_attribute(span_attr, value) |
44 | 43 | except Exception as exc: |
45 | 44 | logger.debug( |
46 | 45 | "RuntimeContextSpanProcessor: error injecting context into span %r: %s", |
|
0 commit comments