Skip to content

Commit

Permalink
fix(sentry-tracing): switch sentry spans on enter and exit
Browse files Browse the repository at this point in the history
  • Loading branch information
saiintbrisson committed Nov 28, 2024
1 parent 605d36d commit 3501378
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 7 deletions.
6 changes: 6 additions & 0 deletions sentry-core/src/performance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -717,6 +717,12 @@ impl Span {
transaction.context.clone()
}

/// Get the current span ID.
pub fn get_span_id(&self) -> protocol::SpanId {
let span = self.span.lock().unwrap();
span.span_id
}

/// Get the status of the Span.
pub fn get_status(&self) -> Option<protocol::SpanStatus> {
let span = self.span.lock().unwrap();
Expand Down
43 changes: 36 additions & 7 deletions sentry-tracing/src/layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -268,15 +268,48 @@ where
// This comes from typically the `fields` in `tracing::instrument`.
record_fields(&sentry_span, data);

sentry_core::configure_scope(|scope| scope.set_span(Some(sentry_span.clone())));

let mut extensions = span.extensions_mut();
extensions.insert(SentrySpanData {
sentry_span,
parent_sentry_span,
});
}

/// Sets entered span as *current* sentry span. A tracing span can be
/// entered and existed multiple times, for example, when using a `tracing::Instrumented` future.
fn on_enter(&self, id: &span::Id, ctx: Context<'_, S>) {
let span = match ctx.span(&id) {
Some(span) => span,
None => return,
};

let extensions = span.extensions();
let SentrySpanData { sentry_span, .. } = match extensions.get::<SentrySpanData>() {
Some(data) => data,
None => return,
};

sentry_core::configure_scope(|scope| scope.set_span(Some(sentry_span.clone())));
}

/// Set exited span's parent as *current* sentry span.
fn on_exit(&self, id: &span::Id, ctx: Context<'_, S>) {
let span = match ctx.span(&id) {
Some(span) => span,
None => return,
};

let extensions = span.extensions();
let SentrySpanData {
parent_sentry_span, ..
} = match extensions.get::<SentrySpanData>() {
Some(data) => data,
None => return,
};

sentry_core::configure_scope(|scope| scope.set_span(parent_sentry_span.clone()));
}

/// When a span gets closed, finish the underlying sentry span, and set back
/// its parent as the *current* sentry span.
fn on_close(&self, id: span::Id, ctx: Context<'_, S>) {
Expand All @@ -286,16 +319,12 @@ where
};

let mut extensions = span.extensions_mut();
let SentrySpanData {
sentry_span,
parent_sentry_span,
} = match extensions.remove::<SentrySpanData>() {
let SentrySpanData { sentry_span, .. } = match extensions.remove::<SentrySpanData>() {
Some(data) => data,
None => return,
};

sentry_span.finish();
sentry_core::configure_scope(|scope| scope.set_span(parent_sentry_span));
}

/// Implement the writing of extra data to span
Expand Down

0 comments on commit 3501378

Please sign in to comment.