在使用 log4net 时,我们可以使用 [%thread]
占位符输出当前线程信息。该信息在多线程程序开发中非常有用,但 Serilog 并未提供用于输出当前线程信息的方式,我们需要自定义一个 Enricher 才可以实现。
在引用了 Serilog 的项目中新增一个 ThreadIdEnricher 类文件,内容如下:
using Serilog.Core;
using Serilog.Events;
using System.Threading;
public class ThreadIdEnricher : ILogEventEnricher
{
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty(
"ThreadId", Thread.CurrentThread.ManagedThreadId.ToString("D4")));
}
}
在配置 Serilog 时,需要将 ThreadIdEnricher 加入到配置中,并添加占位符:
private static void CreateLog()
{
// 配置 Serilog
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.Enrich.With<ThreadIdEnricher>()
// 配置日志输出到控制台
.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] [{ThreadId}] {Message:lj}{NewLine}{Exception}")
// 创建 logger
.CreateLogger();
}
输出 Hello World 时,效果如下:

可以看到,控制台中输出了当前线程的 ID 信息。
以上完整代码可以在 https://gitee.com/coderbusy/demo/tree/master/serilog-thread-id-enricher 中找到。