Search code examples
.net-coretrace

Set TraceId on Activity


I have a worker service which listens on a message broker and gets triggered when a message arrives. Once it is triggered I manually create an Activity and copy SpanId from the incoming message into the local Activity.ParentID. However, the local Trace Id is generated anew and I lose the ability to trace across services. I cannot manually copy the Trace Id over because Activity.TraceId is read only.

Activity.DefaultIdFormat = ActivityIdFormat.W3C;
using var activity = new Activity("Consumer");
activity.SetParentId(messageFromBroker.ParentId);
activity.Start();
_logger.LogInformation("foo foo foo");
// ... do some processing...
activity.Stop();

How can I create a new Activity and manually set TraceId?


Solution

  • It seems TraceId cannot be set explicitly, but what you can do is provide entire traceparent header, as below:

    activity.SetParentId("00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01");