Serilog – Add thread ID to the log file

Serilog is more or less the default file logger when developing .NET Core applications. The simple logger can easily be modified to – for example – add the thread ID.

FIRST THINGS FIRST: THE SERILOG NUGET PACKAGES

You need these packages in order for Serilog to appear before you:

Serilog.AspNetCore
Serilog.Sinks.File

STEP 1: ADD SERILOG TO THE LOGGING:

You need to add Serilog when initializing the services:

private static IServiceProvider InitializeServiceCollection()
{
  var services = new ServiceCollection()
    .AddLogging(configure => configure
      .AddSerilog()
      .AddConsole()
    )
    .BuildServiceProvider();
  return services;
}

STEP 2: CREATE A ILOGEVENTENRICHER

The ILogEventEnricher is the Serilog way of adding properties that can be used when logging:

public class ThreadIDEnricher : ILogEventEnricher
{
  public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
  {
    logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty(
      "ThreadID", Thread.CurrentThread.ManagedThreadId.ToString("D4")));
  }
}

STEP 3: ADD THE ENRICHER AND USE IT WHEN LOGGING:

public static void Initialize(IServiceProvider services)
{
  string logFileName = "log.log";

  Serilog.Log.Logger = new LoggerConfiguration()
    // Adding the enricher
    .Enrich.With(new ThreadIDEnricher())
    .WriteTo.File("log.log", 
                  rollingInterval: RollingInterval.Day, 
                  // Adding the threadID with {ThreadID} to the output string
                  outputTemplate: "{Timestamp:HH:mm:ss.fff} ({ThreadID}) {Message:lj}{NewLine}{Exception}")
    .CreateLogger();
}

THE USAGE:

// Replace "Program" with your own instance name
var logger = services.GetService<ILoggerFactory>().CreateLogger<Program>();
logger.LogError("This is an error");

The output will look like this, with the thread ID in parenthesis just after the timestamp:

11:22:48.149 (0001) Application.Started
11:22:48.232 (0001) An error happened.
11:22:49.236 (0002) Another error happened.
11:22:49.239 (0003) Application.Ended

MORE TO READ:

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in .NET Core, c#, Microsoft Azure and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.