Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Always include request GUID/Correlation Id in IIS 7+ logs

We need to watch requests/failures through response to the client. We've determined that using a uniquely generated correlation id is best.

As an entry point to one or more API's, our .NET Web API 2 application receives requests via IIS 7+. To track a request (whether it failed OR succeeded), we need for the IIS log files to include unique GUID (assuming an ActivityID). We know once we are within the Web API, we can gather the ActivityId from CorrelationManager.ActivityId but at the host/server level, we need this to be reported.

... For all requests, successful or failed, how do we get IIS to start with including its own unique correlation identifier in logs it touches?

like image 592
David Garza Avatar asked Sep 15 '25 17:09

David Garza


1 Answers

In IIS, you can add custom logging fields based on request headers, response headers and server variables. So, one option is to add the ActivityId to the response headers, as described here.

For ASP MVC and SerilogWeb.Classic, add this to Global.asax.cs:

protected void Application_EndRequest(object sender, EventArgs e)
{
    if (sender is HttpApplication application)
    {
        var httpResponse = application.Context.Response;

        if (httpResponse.HeadersWritten)
        {
            return;
        }

        // Fetch correlation ID used by Serilog and add onto response header, so that IIS can include it in IIS request log
        if (httpResponse.Headers["X-Correlation-Id"] == null && HttpRequestIdEnricher.TryGetCurrentHttpRequestId(out var correlationId))
        {
            httpResponse.Headers.Add("X-Correlation-Id", correlationId.ToString());
        }
    }
}

However, you would replace correlationId with your ActivityId.

Then, set up IIS logging like so:

IIS logging using custom fields

like image 192
Sheldor the conqueror Avatar answered Sep 18 '25 11:09

Sheldor the conqueror