|  | 
|  | 1 | +import sentry_sdk | 
|  | 2 | +from sentry_sdk.integrations import Integration, DidNotEnable | 
|  | 3 | +from sentry_sdk.scope import add_global_event_processor | 
|  | 4 | + | 
|  | 5 | +try: | 
|  | 6 | +    from opentelemetry import trace | 
|  | 7 | +except ImportError: | 
|  | 8 | +    raise DidNotEnable("opentelemetry is not installed") | 
|  | 9 | + | 
|  | 10 | +from typing import TYPE_CHECKING | 
|  | 11 | + | 
|  | 12 | +if TYPE_CHECKING: | 
|  | 13 | +    from typing import Optional | 
|  | 14 | + | 
|  | 15 | +    from sentry_sdk._types import Event, Hint | 
|  | 16 | + | 
|  | 17 | + | 
|  | 18 | +class OtlpIntegration(Integration): | 
|  | 19 | +    identifier = "otlp" | 
|  | 20 | + | 
|  | 21 | +    @staticmethod | 
|  | 22 | +    def setup_once(): | 
|  | 23 | +        # type: () -> None | 
|  | 24 | +        @add_global_event_processor | 
|  | 25 | +        def link_trace_context_to_error_event(event, hint): | 
|  | 26 | +            # type: (Event, Optional[Hint]) -> Optional[Event] | 
|  | 27 | +            integration = sentry_sdk.get_client().get_integration(OtlpIntegration) | 
|  | 28 | +            if integration is None: | 
|  | 29 | +                return event | 
|  | 30 | + | 
|  | 31 | +            if hasattr(event, "type") and event["type"] == "transaction": | 
|  | 32 | +                return event | 
|  | 33 | + | 
|  | 34 | +            otel_span = trace.get_current_span() | 
|  | 35 | +            if not otel_span: | 
|  | 36 | +                return event | 
|  | 37 | + | 
|  | 38 | +            ctx = otel_span.get_span_context() | 
|  | 39 | + | 
|  | 40 | +            if ( | 
|  | 41 | +                ctx.trace_id == trace.INVALID_TRACE_ID | 
|  | 42 | +                or ctx.span_id == trace.INVALID_SPAN_ID | 
|  | 43 | +            ): | 
|  | 44 | +                return event | 
|  | 45 | + | 
|  | 46 | +            contexts = event.setdefault("contexts", {}) | 
|  | 47 | +            contexts.setdefault("trace", {}).update( | 
|  | 48 | +                { | 
|  | 49 | +                    "trace_id": trace.format_trace_id(ctx.trace_id), | 
|  | 50 | +                    "span_id": trace.format_span_id(ctx.span_id), | 
|  | 51 | +                    "status": "ok",  # TODO | 
|  | 52 | +                } | 
|  | 53 | +            ) | 
|  | 54 | + | 
|  | 55 | +            return event | 
0 commit comments