Adding correlation id using Serilog to Seq in .NET Standard Web Api

Viewed 2020

This is my first question but please advise if I can make improvements to the question.

I have a .NET Standard Web Api that uses Serilog to log requests to a Seq server. I want to add a correlation id to responses to use on the front end to track requests.

Here is the logging configuration Global.asax:

Log.Logger = new LoggerConfiguration()
             .Enrich.With<HttpRequestIdEnricher>()
             .Enrich.FromLogContext()
             .WriteTo.Seq(ConfigurationManager.AppSettings["Seq:Url"])
             .CreateLogger();

I have a message handler which adds a correlation id to all requests:

public class AddCorrelationIdToResponseHandler : DelegatingHandler
    {
        private const string CorrelationIdHeaderName = "X-Correlation-Id";

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var responseMessage = await base.SendAsync(request, cancellationToken);
            var correlationId = request.GetCorrelationId().ToString();
            
            responseMessage
                .Headers
                .Add(CorrelationIdHeaderName, correlationId);

            return responseMessage;
        }
    }

The problem is the enricher (understandably) doesn't add the HttpRequestId to the response headers so I cannot use it in the front end and I cannot get the correlation id here into the Seq logs.

Here's what I have tried adding to the handler:

LogContext.PushProperty(CorrelationIdHeaderName, correlationId)
Log.ForContext(CorrelationIdHeaderName, correlationId)

both to no avail.

I have also wrapped the entire handler in a using statement with the LogContext statement.

Seq entry example here

I think the issue might be that the log context isn't valid here since the actual logging happens automatically in a different place.

Is there a way I can get access to the HttpRequestId to add it to the header or otherwise how can I can the correlation id to display as a property in the Seq logs? As a last resort, can one switch off the automatic Web Api logging and log the requests manually using Log.Information or Log.Error (in which case the log context should work in theory)?

Any assistance will be greatly appreciated.

0 Answers
Related