Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Link errors to OTel spans #1787

Merged
merged 10 commits into from Dec 19, 2022
34 changes: 34 additions & 0 deletions sentry_sdk/integrations/opentelemetry/span_processor.py
Expand Up @@ -6,6 +6,7 @@
from opentelemetry.trace import ( # type: ignore
format_span_id,
format_trace_id,
get_current_span,
SpanContext,
Span as OTelSpan,
SpanKind,
Expand All @@ -16,6 +17,7 @@
SENTRY_BAGGAGE_KEY,
SENTRY_TRACE_KEY,
)
from sentry_sdk.scope import add_global_event_processor
from sentry_sdk.tracing import Transaction, Span as SentrySpan
from sentry_sdk.utils import Dsn
from sentry_sdk._types import MYPY
Expand Down Expand Up @@ -45,6 +47,38 @@ def __new__(cls):

return cls.instance

def __init__(self):
# type: () -> None
@add_global_event_processor
def link_trace_context_to_error_event(event, hint):
antonpirker marked this conversation as resolved.
Show resolved Hide resolved
# type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any]
if hasattr(event, "type") and event["type"] == "transaction":
return event

otel_span = get_current_span()
if not otel_span:
return event

ctx = otel_span.get_span_context()
trace_id = format_trace_id(ctx.trace_id)
span_id = format_span_id(ctx.span_id)

invalid_span = (
trace_id == "00000000000000000000000000000000"
antonpirker marked this conversation as resolved.
Show resolved Hide resolved
or span_id == "0000000000000000"
)
if invalid_span:
return event

sentry_span = self.otel_span_map.get(span_id, None)
if not sentry_span:
return event

contexts = event.setdefault("contexts", {})
contexts.setdefault("trace", {}).update(sentry_span.get_trace_context())

return event

def on_start(self, otel_span, parent_context=None):
# type: (OTelSpan, SpanContext) -> None
hub = Hub.current
Expand Down