Quantcast
Channel: Brian Pedersen's Sitecore and .NET Blog
Viewing all articles
Browse latest Browse all 285

Serilog – Add thread ID to the log file

$
0
0

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:


Viewing all articles
Browse latest Browse all 285

Trending Articles