Reputation: 20679
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?
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
Reputation: 4957
Here is an idea - that may hold water:
Activity.Current?.Id
is more relevant - what sub-action failed?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
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