Add Thread ID to the Log File using Serilog

By FoxLearn 1/14/2025 9:11:33 AM   10
To add the Thread ID to the log file using Serilog in an ASP.NET Core application, you can follow these steps:

Serilog is commonly used as the default file logger when developing .NET Core applications. It offers a simple logging setup that can be easily customized, such as adding the thread ID to log entries.

First, ensure you have the necessary Serilog packages installed.

Serilog.AspNetCore
Serilog.Sinks.File

Add Serilog to Logging

To integrate Serilog into your logging configuration, you'll first need to add it when initializing the services:

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

Create an ILogEventEnricher

The ILogEventEnricher is Serilog’s way of adding custom properties to log events. In this case, we'll use it to add the thread ID:

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

Add the Enricher and Use it in Logging

Now, you’ll need to add the ThreadIDEnricher to your Serilog configuration and specify the output format that includes the thread ID.

public static void Initialize(IServiceProvider services)
{
    string logFileName = "log.log";
    
    Serilog.Log.Logger = new LoggerConfiguration()
        // Add the enricher
        .Enrich.With(new ThreadIDEnricher())
        .WriteTo.File("log.log", 
            rollingInterval: RollingInterval.Day, 
            // Include ThreadID in the output template
            outputTemplate: "{Timestamp:HH:mm:ss.fff} ({ThreadID}) {Message:lj}{NewLine}{Exception}")
        .CreateLogger();
}

Once Serilog is set up, you can use the logger to log messages, and the thread ID will be automatically included in the log output:

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

Output:

With the above configuration, your log file will include entries like this, with the thread ID appearing in parentheses after the timestamp:

10:12:48.148 (0001) Application.Started
10:12:48.231 (0001) An error happened.
10:12:49.237 (0002) Another error happened.
10:12:49.238 (0003) Application.Ended

For new ASP.NET Core

First, ensure you have the necessary Serilog packages installed. You need Serilog, Serilog.Extensions.Logging, and Serilog.Sinks.File.

You can install them via NuGet Package Manager or by running the following commands in the Package Manager Console:

Install-Package Serilog
Install-Package Serilog.Extensions.Logging
Install-Package Serilog.Sinks.File

In your ASP.NET Core project, open Program.cs and configure Serilog to include the Thread ID in the log output.

var builder = WebApplication.CreateBuilder(args);

// Configure Serilog
Log.Logger = new LoggerConfiguration()
    .WriteTo.Console()
    .WriteTo.File("logs/log.txt", rollingInterval: RollingInterval.Day)
    .Enrich.WithThreadId() // This adds the Thread ID to the logs
    .MinimumLevel.Information()
    .CreateLogger();

builder.Host.UseSerilog(); // Use Serilog as the logging provider

In the configuration above, Enrich.WithThreadId() adds the Thread ID to each log entry. This ensures that every log record has information about which thread is executing the log statement.

The output will include something like this:

[2025-01-14 12:34:56.789][ThreadId: 5] Information: Starting application...

Use Logging in Your Application

Now, in your controllers or services, you can log messages as usual.

For example:

using Microsoft.AspNetCore.Mvc;
using Serilog;

public class HomeController : Controller
{
    public IActionResult Index()
    {
        Log.Information("Hello, this is a log message with Thread ID.");
        return View();
    }
}

When you run the application, Serilog will log messages to the logs/log.txt file (or any file path you've configured), and each log entry will include the Thread ID.