lonix
lonix

Reputation: 20679

Difference between HttpContext.TraceIdentifier and Activity.Current.Id

I use a "trace id" in logs. Advice on the aspnet repo and here on SO is to get a traceid from HttpContext.TraceIdentifier.

But when the framework creates a ProblemDetails for a validation failure, it uses Activity.Current?.Id.

Examples:

var traceId1 = Activity.Current?.Id;        // OWZ4G27FO6UWH:00000003
var traceId2 = HttpContext.TraceIdentifier; // 00-2a8ee37903e657e3a95b41178dafc56e-91b02006afcf3133-00

I'm worried that my logs use one type of trace id, and the framework uses another - and when I find myself needing to analyse logs I'll have a problem.

How do these differ? Which should I use? Which type does the framework typically use?

UPDATE

I asked on the repo too, and they closed it without explanation. If you have time, please open a new issue, and give us the link so we can upvote your issue.

Upvotes: 17

Views: 5626

Answers (2)

johnml1135
johnml1135

Reputation: 4957

Here is an idea - that may hold water:

  • Tasks where the aspnetcore is failing may or may not be associated with a HTTP request - but rather the Activity.Current?.Id is more relevant - what sub-action failed?
  • Users of aspnetcore are often more concerned about which http request failed than which aspect of the underlying framework, hence the advice for httpContext?.TraceIdentifier.

Therefore, the appearance of a discrepancy may just be a different perspective from the core libraries and the custom server code as to what is the most appropriate ID. So, most users should probably just follow the standard advice and use httpContext?.TraceIdentifier, or likely:

// Use http first to trace to client call, if available
// If not, fall back on the thread ID
var traceId = httpContext?.TraceIdentifier ?? Activity.Current?.Id;

Upvotes: 4

Zhi Lv
Zhi Lv

Reputation: 21421

The HttpContext.TraceIdentifier Property: Gets or sets a unique identifier to represent this request in trace logs.

The Activity.Current Property: Gets or sets the current operation (Activity) for the current thread.

var traceId = Activity.Current?.Id ?? httpContext?.TraceIdentifier;

From the source code, we can see that it will use the Activity Id as the first choice, if the Activity Id is null, it will use the httpContext?.TraceIdentifier, you can also use this method to set the trace id.

Upvotes: 4

Related Questions