.NET Core Log Correlation

Correlating log entries across multiple API's easily and efficiently without a whole lot of extra code in the way

One of my primary personal goals this year is to become better at logging. One of the things I'm struggling with finding any information on is correlating log entries across multiple API's easily and efficiently without a whole lot of extra code in the way.

For correlating the calls between different tiers, I have 4 main requirements. These will be in 4 separate posts.

  1. Send an ID between API calls and have it included in the log files. This is a must, and primary concern.
  2. The ID should be in the same property in all logs.
  3. Easily access the ID.
  4. When possible, it should automatically be added to the HttpClient requests.

I'm doing pretty much everything in .NET Core now, so we will be dealing only with that.

In this series I am passing around a header named X-SessionId to the backend services. The property name in the logs that I want is SessionId. This is just an example, and not a session id stored in a session. It changes on every request, much like the context.TraceIdentifier property does. I'm using it strictly for demo purposes. If you want the frontend site to pass the id from the session, in the DefaultSessionIdAccessor:GetSessionId() return the value of this._httpContextAccessor.HttpContext.Session.Id. Be sure to setup all of the session related stuff for the project.

The benefits to learning and using log correlation are extreme, especially in a micro-service world. Without it, it's like having 15,000 pieces of 15 huge puzzles that you must put together all at the same time.

I have a GitHub repository containing a full working example of the code in this series. The code in this series is a direct copy from this example project.

https://github.com/veccsolutions/Vecc.LogCorrelation.Example