diff --git a/CHANGELOG.md b/CHANGELOG.md index e58d84883..3749b4821 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,8 @@ end ``` +- Add global event processor in OpenTelemetry `SpanProcessor` to link errors with transactions [#1983](https://github.com/getsentry/sentry-ruby/pull/1983) + ### Bug Fixes diff --git a/sentry-opentelemetry/lib/sentry/opentelemetry/span_processor.rb b/sentry-opentelemetry/lib/sentry/opentelemetry/span_processor.rb index 89929d4a4..da78e383e 100644 --- a/sentry-opentelemetry/lib/sentry/opentelemetry/span_processor.rb +++ b/sentry-opentelemetry/lib/sentry/opentelemetry/span_processor.rb @@ -18,6 +18,7 @@ class SpanProcessor < ::OpenTelemetry::SDK::Trace::SpanProcessor def initialize @span_map = {} + setup_event_processor end def on_start(otel_span, parent_context) @@ -152,6 +153,19 @@ def update_span_with_otel_data(sentry_span, otel_span) sentry_span.set_op(op) sentry_span.set_description(description) end + + def setup_event_processor + Sentry.add_global_event_processor do |event, _hint| + span_context = ::OpenTelemetry::Trace.current_span.context + next event unless span_context.valid? + + sentry_span = @span_map[span_context.hex_span_id] + next event unless sentry_span + + event.contexts[:trace] ||= sentry_span.get_trace_context + event + end + end end end end diff --git a/sentry-opentelemetry/spec/sentry/opentelemetry/span_processor_spec.rb b/sentry-opentelemetry/spec/sentry/opentelemetry/span_processor_spec.rb index 633d75f1e..bcd5a039e 100644 --- a/sentry-opentelemetry/spec/sentry/opentelemetry/span_processor_spec.rb +++ b/sentry-opentelemetry/spec/sentry/opentelemetry/span_processor_spec.rb @@ -78,6 +78,23 @@ it 'raises error on instantiation' do expect { described_class.new }.to raise_error(NoMethodError) end + + context 'global event processor' do + let(:event_processor) { Sentry::Scope.global_event_processors.first } + let(:event) { Sentry::Event.new(configuration: Sentry.configuration) } + let(:hint) { {} } + + before { subject.on_start(root_span, empty_context) } + + it 'sets trace context on event' do + OpenTelemetry::Context.with_current(root_parent_context) do + event_processor.call(event, hint) + expect(event.contexts).to include(:trace) + expect(event.contexts[:trace][:trace_id]).to eq(root_span.context.hex_trace_id) + expect(event.contexts[:trace][:span_id]).to eq(root_span.context.hex_span_id) + end + end + end end describe '#on_start' do