来自上下文的 Serilog 丰富不起作用

Serilog enrichment from context not working

我有一个 ASP .NET Core 应用程序,我正在尝试使用 属性 丰富 Serilog 记录器并通过方法调用传递它。 我已经使用 Serilog.Context 来丰富它但无济于事,日志中不存在 属性。

计划

Log.Logger = new LoggerConfiguration().Enrich.FromLogContext()
                .WriteTo.File(logpath)
                .CreateLogger();

控制器

public class SomeController{

   public ILogger logger=Log.ForContext<SomeController>();
   private SomeService Service;

   public SomeController(SomeService serv)
   {
      this.service=serv;
   }

   [HttpGet]
   public async Task DoSomething()
   {
          string corellationId=Guid.NewGuid().ToString();
          LogContext.PushProperty("id",corellationId);
          service.Run();
    }
}

服务

class SomeService
{
   private ILogger logger=Log.ForContext<SomeService>();
   public void Run()
   {
       logger.Information("I AM NOT SEEING the ID from upstream !");
   }
}

基本上我希望 SomeService 的日志具有上游提供的 ID(控制器操作)。 我想要什么:

"[id] [value]"+ "[SomeService log]" 

P.S 如果重要,服务通过依赖注入注入。

您需要在 your outputTemplate 中使用 Properties 标记,例如

var mt = "{LogLevel:u1}|{SourceContext}|{Message:l}|{Properties}{NewLine}{Exception}"

当您格式化接收器的输出时,例如:

 .WriteTo.File(logpath, outputTemplate: mt)

(旁白:你应该是 using the LogContext.Push return value