sentry-dotnet
sentry-dotnet copied to clipboard
Allow defining the "Active Span"
Problem Statement
Integrations such as SentryHttpMesageHandler rely on
_hub.GetSpan()?.StartChild
to create a span. This on the Hub today is wired as:
public ISpan? GetSpan() => Transaction?.GetLastActiveSpan() ?? Transaction;
This means I can't set a specific span to get returned from GetSpan. When parallelizing work, the parent/child relationship becomes messy since there are multiple spans "active" and relying on the root transaction isn't possible to find out which one it is.
Solution Brainstorm
When we're propagating the span explicitly downstream. A user can push a scope and set that new span as the active one. So integrations can find the correct parent span.
For example _hub.SetActiveSpan(span)
@bruno-garcia so given adding SetActiveSpan to IHub would be a breaking change. is you plan to add this in the next major?
Related to #1679.
#1679 should be fixed after applying this enhancement to the AspNetCore integration. These two should be done together.
Some time has passed and I recently took another look at this. We can achieve this goal without modifying the hub. Rather, we just need to implement setSpan on the scope as already defined in the Unified SDK with https://develop.sentry.dev/sdk/performance/#scope-changes
I propose rather than ISpan? GetSpan() and void SetSpan(ISpan?), we just use property conventions and go with ISpan? Span {get; set;}. We can obsolete and forward the existing Scope.GetSpan.
When used in conjunction with WithScope / WithScopeAsync (reintroduced in 3.31.0 with #2303), this make a much simpler way to achieve the same goal.
var span = SentrySdk.GetSpan();
Parallel.ForEach(items, item =>
{
SentrySdk.WithScope(scope =>
{
scope.Span = span;
// Do some work that might generate new child spans, etc.
// They'll all be created from the span set on the scope.
});
});
This works well for async also. See my notes and example here: https://github.com/getsentry/sentry-dotnet/issues/1679#issuecomment-1543274341
Fixed in #2364