Search code examples
asp.net-coreserilog

HttpContext.TraceIdentifier is always same (and a Guid)


I am setting up logging for my .NET Core webapi and want to have a unique Id for one request.

After some googling I have found out that Serilog uses HttpContext.TraceIdentifier for that purpose and it should look something like "0HL0GJPLR7AOD".

If I set a breakpoint in the controller method I get the HttpContext.TraceIdentifier to be a Guid, and whats worse, its the same every time, not one per request (800000ad-0002-fb00-b63f-84710c7967bb).

This is also what is displayed in serilog as "RequestId", but my main question is why is HttpContext.TraceIdentifier not on the format "some text" and why is it same every request?


Solution

  • This will likely be down to where you are hosting your app, the trace identifier ultimately comes from a feature of the hosting platform. If you run your app in Kestrel, e.g. by using the default profile (usually named the same as your project) you'll see a format of ConnectionID:Count (see this answer).

    Here's an example of the feature when running as above:

    Running on Kestrel

    If you run using IIS/Express you'll see a GUID, and in my testing it is unique per request... Here's the same example on IIS Express:

    Running on IIS Express

    Btw, you could set the TraceIdentifier yourself and/or you might also want to look at the Activity class. This takes precedence over the TraceIdentifier generally, e.g. in a default error page:

    public class ErrorModel : PageModel
    {
        public string RequestId { get; set; }
    
        public void OnGet()
        {
            RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
        }
    }