Logging

I have had the misfortune of delving into logging a lot lately. To save time for next time I will write down the findings here.

My goals are simple. A couple of sites and APIs log into the same log aggregator, could be loggly, seq or graylog for instance. Given that I supply a correlation ID, I want to be able to tag all log entries related to one user as it travels through the system. This isn’t even on the bare minimum Charity Majors event logging, this is just glorified text but searchable with fields.

As of the date today, I want to be clear that for .NET, Serilog is best. Log4net is out since a long time ago, NLog tried but cannot explain how to do structured logging, so will have to be excused. Serilog has a more pleasant interface t and although I have struggled in the past to get the log context to enrich properly and had to resort to the Microsoft log abstraction combined with Serilog.AspNetCore to succeed and had problems getting the loggly sink working at all since docs skipped the need for the loggly-csharp nuget package. Still, it keeps winning, on old .NET Framework as well as .NET Core.

Setting up the Correlation ID has two parts. The first part is a piece of middleware in the request pipeline that wraps the call to the next stage in the pipeline in a using() statement. Here you extract the correlation ID from the caller or supply a suitable unique default for this call.

Then you create a message handler for setting a correlation ID on the outgoing HttpClient call. You can use the IHttpContextAccessor to get the incoming CorrelationId or the same default as earlier and map the message handler to any HttpClients you have defined in the projects.

Leave a Reply

Your email address will not be published. Required fields are marked *