Skip to content
Merged
Next Next commit
EF Core and SqlClient instrumentation enabled at the same time produc…
…e wrong spans
  • Loading branch information
zivaninstana authored and martincostello committed Jun 24, 2025
commit 2f2425e6066edbc68e63248e24e715041d425a19
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ internal sealed class EntityFrameworkDiagnosticListener : ListenerHandler
internal static readonly Assembly Assembly = typeof(EntityFrameworkDiagnosticListener).Assembly;
internal static readonly string ActivitySourceName = Assembly.GetName().Name;
internal static readonly string ActivityName = ActivitySourceName + ".Execute";
internal static readonly ActivitySource SqlClientActivitySource = new(ActivitySourceName, Assembly.GetPackageVersion());
internal static readonly ActivitySource EntityFrameworkActivitySource = new(ActivitySourceName, Assembly.GetPackageVersion());

private readonly PropertyFetcher<object> commandFetcher = new("Command");
private readonly PropertyFetcher<object> connectionFetcher = new("Connection");
Expand Down Expand Up @@ -59,7 +59,7 @@ public override void OnEventWritten(string name, object? payload)
{
case EntityFrameworkCoreCommandCreated:
{
activity = SqlClientActivitySource.StartActivity(ActivityName, ActivityKind.Client);
activity = EntityFrameworkActivitySource.StartActivity(ActivityName, ActivityKind.Client);
if (activity == null)
{
// There is no listener or it decided not to sample the current request.
Expand Down Expand Up @@ -168,7 +168,7 @@ public override void OnEventWritten(string name, object? payload)
return;
}

if (activity.Source != SqlClientActivitySource)
if (activity.Source != EntityFrameworkActivitySource)
{
return;
}
Expand Down Expand Up @@ -267,12 +267,18 @@ public override void OnEventWritten(string name, object? payload)
return;
}

if (activity.Source != SqlClientActivitySource)
if (activity.Source == EntityFrameworkActivitySource)
{
return;
activity.Stop();
}

activity.Stop();
// from some reason this EF event comes before SQLClient SqlMicrosoftAfterExecuteCommand event
// EF span should not be parrent of any other span except SQLClient, because of that it can be closed safetly
// can result in a slightly strange timeline where the EF span finishes before its child SQLClient but based on EventSources it is true
if (activity.Parent?.Source == EntityFrameworkActivitySource)
{
activity.Parent.Stop();
}
}

break;
Expand All @@ -285,7 +291,7 @@ public override void OnEventWritten(string name, object? payload)
return;
}

if (activity.Source != SqlClientActivitySource)
if (activity.Source != EntityFrameworkActivitySource)
{
return;
}
Expand Down