Skip to content

Instantly share code, notes, and snippets.

@x789
Created October 13, 2022 06:53
Show Gist options
  • Save x789/4a8b312f1ef5cc9aa01488312cf2a296 to your computer and use it in GitHub Desktop.
Save x789/4a8b312f1ef5cc9aa01488312cf2a296 to your computer and use it in GitHub Desktop.
ASP.NET Core + W3C TraceContext
// Mapping of .NET Activity Context to W3C TraceContext
var traceId = Activity.Current!.ParentId; // W3C 3.2.2.3 trace-id
var parentId = Activity.Current!.ParentSpanId; // W3C 3.2.2.4 parent-id
var spanId = Activity.Current!.SpanId; // This service's span-id. Will become parent-id of next call
// The W3C says that a span is the execution of a client request (chapter 3.2.2.4). By default, .NET creates a span for each created (internal) activity.
// This can lead to traceparent headers containing span-ids whose placement in the execution flow is not possible.
// Since .NET6, DistributedContextPropagators can be used to control the creation of the traceparent header. Use the built-in PassThroughPropagator that sets the incoming span-id as parent-id and not the id of the latest activity.
// Details at https://devblogs.microsoft.com/dotnet/dotnet-6-networking-improvements/#diagnostics
DistributedContextPropagator.Current = DistributedContextPropagator.CreatePassThroughPropagator();
// Activate W3C compatible headers.
// Details at https://devblogs.microsoft.com/dotnet/improvements-in-net-core-3-0-for-troubleshooting-and-monitoring-distributed-apps/#w3c-trace-context-support
Activity.DefaultIdFormat = ActivityIdFormat.W3C;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment