ASP.NET Core – tracking flow of requests with NLog

1. Introduction

A while ago I wrote an article about using MappedDiagnosticsLogicalContext for tracking request flow in your application. As we are moving our project to ASP.NET Core, I wanted to keep that functionality in place. Unfortunately, MDLC layout renderer is not available in that framework anymore(when targeting .NET Core). Luckily, there are two other renderers which can be used as a replacement:

  • aspnet-traceidentifier
  • aspnet-item

2. Configuring NLog

Before I dig into details of layout renderers mentioned above, we have to configure ASP.NET Core to use NLog as a logger. First of all, we need to grab NLog.Web.AspNetCore NuGet package. Once the package is installed we have to manually add NLog.config to the project (the file won’t be added automatically by NuGet installer). The next step is to configure NLog with our config, then configure NLogWeb and finally register NLog in LoggingFactory. All of these steps should be done in Startup class.

The final step required for NLog to work is to register HttpContextAccessor in IoC container of your choice. If you use the build one, you can do it like that

3. Using aspnet-traceidentifier renderer

Aspnet-traceidentifier layout renderer allows you to obtain value of TraceIdentifier property from current HttpContext. TraceIdentifier is basically unique id which identifies the request. The renderer can be used as follows

From now on (without any additional configuration) every log entry logged (once HttpContext is created), will contain TraceIdentifier.

4. Using aspnet-item renderer

If for some reasons we don’t like to use TraceIdentifier as our CorrelationId, we can leverage aspnet-item renderer, which basically allows you to read data from HttpContext.Items collection. However in that case, we are responsible for providing and storing unique identifier of request in HttpContext.Items. Fortunately it is pretty straightforward to do with custom middleware.

Of course we have to also use this middleware in our application so we have to add following line

in configure method of our Startup class. Having all the pieces in place, now we can append CorrelationId read from HttpContext.Items to our log entries with following configuration

From now on, CorrelationId will be automatically added to our log entries

6. It works in multithreading scenarios

If you take a closer look at logs presented above, you will see that both of the renderers can log proper CorrelationId/TraceId regardless of the thread from which the logger was called. This is possible thanks to implementation of HttpContextAccessor which uses AsyncLocal under the hood, which allows you to persist data across threads.

Source code for this post can be found here

ASP.NET Core – tracking flow of requests with NLog

3 thoughts on “ASP.NET Core – tracking flow of requests with NLog

  1. Chris Darrigo says: 

    I’m getting an error from nLog – Error parsing layout aspnet-traceidentifier will be ignored. Exception: System.ArgumentException: LayoutRenderer cannot be found: ‘aspnet-traceidentifier’. Is NLog.Web not included?

    my asp.net core app is using nLog.Web.AspNetCore v4.4.0 and my startup looks like this.

    public class Startup
    {
    public Startup(IHostingEnvironment env)
    {

    env.ConfigureNLog(“nlog.config”);
    }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {

    services.AddSingleton();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {

    loggerFactory.AddNLog();
    app.AddNLogWeb();
    }

    and my layout:

    Any thoughts why it wouldn’t be able to resolve the aspnet-traceidentifier property?

    1. TPodolak says: 

      Looks like NLog layout was removed from your comment. The C# part looks fine for me, as I can’t see your NLog.config , make sure that it contains
      <extensions>
      <add assembly="NLog.Web.AspNetCore"/>
      </extensions>

Comments are closed.