|
| 1 | +from collections.abc import Mapping |
| 2 | +from typing import Any |
| 3 | + |
| 4 | +from zcs.core.session import RequestState, request_context |
| 5 | + |
| 6 | + |
| 7 | +def _safe_set_attribute(span, key: str, value: Any) -> None: |
| 8 | + if value is None: |
| 9 | + return |
| 10 | + |
| 11 | + if isinstance(value, (str, bool, int, float)): |
| 12 | + span.set_attribute(key, value) |
| 13 | + return |
| 14 | + |
| 15 | + span.set_attribute(key, str(value)) |
| 16 | + |
| 17 | + |
| 18 | +def set_trace_attributes( |
| 19 | + request_state: RequestState | None = None, |
| 20 | + *, |
| 21 | + app_name: str | None = None, |
| 22 | + app_environment: str | None = None, |
| 23 | + app_version: str | None = None, |
| 24 | + extra_attributes: Mapping[str, Any] | None = None, |
| 25 | +) -> None: |
| 26 | + """Set trace attributes from app metadata and request context.""" |
| 27 | + try: |
| 28 | + from opentelemetry import trace |
| 29 | + except ImportError: |
| 30 | + return |
| 31 | + |
| 32 | + span = trace.get_current_span() |
| 33 | + if not span: |
| 34 | + return |
| 35 | + |
| 36 | + span_context = span.get_span_context() |
| 37 | + if not span_context or not span_context.is_valid: |
| 38 | + return |
| 39 | + |
| 40 | + current_state = request_state or request_context.get() |
| 41 | + |
| 42 | + _safe_set_attribute(span, "app_name", app_name) |
| 43 | + _safe_set_attribute(span, "app_environment", app_environment) |
| 44 | + _safe_set_attribute(span, "app_version", app_version) |
| 45 | + |
| 46 | + if not current_state: |
| 47 | + if extra_attributes: |
| 48 | + for key, value in extra_attributes.items(): |
| 49 | + _safe_set_attribute(span, key, value) |
| 50 | + return |
| 51 | + |
| 52 | + _safe_set_attribute(span, "request_op_code", current_state.getOpCode()) |
| 53 | + _safe_set_attribute(span, "request_request_id", current_state.getRequestId()) |
| 54 | + _safe_set_attribute(span, "request_follia_module", current_state.getFolliaModule()) |
| 55 | + |
| 56 | + auth_info = current_state.getAuthInfo() |
| 57 | + if auth_info: |
| 58 | + _safe_set_attribute(span, "auth_client_id", auth_info.client_id) |
| 59 | + _safe_set_attribute(span, "auth_tenant_id", auth_info.tenant_id) |
| 60 | + _safe_set_attribute(span, "auth_company_id", auth_info.company_id) |
| 61 | + _safe_set_attribute(span, "auth_user_id", auth_info.user_id) |
| 62 | + _safe_set_attribute(span, "auth_user_mail", auth_info.user_email) |
| 63 | + |
| 64 | + if extra_attributes: |
| 65 | + for key, value in extra_attributes.items(): |
| 66 | + _safe_set_attribute(span, key, value) |
0 commit comments