【问题标题】:Serilog enrichment from context not working从上下文中丰富的 Serilog 不起作用
【发布时间】:2022-05-25 21:18:41
【问题描述】:

我有一个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如果重要的话,服务会通过依赖注入来注入。

【问题讨论】:

    标签: asp.net-core logging serilog


    【解决方案1】:

    您需要在your outputTemplate 中使用Properties 令牌,例如

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

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

     .WriteTo.File(logpath, outputTemplate: mt)
    

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

    【讨论】:

    • 所以为了让我在格式中添加string,这样的表格就足够了:"{Timestamp:Yy:Mm:dd HH:mm:ss} [{Level:u3}] {corellationId} {Message}?
    • 是的,如果您总是使用using LogContext.Push("corellationId",value),那么它将显示每条消息的值({Properties} 标记显示消息或消息模板中未引用的所有属性)跨度>
    • 我只想为每个请求绑定一次属性,当我的请求进入ASP NET Controller 然后出现在嵌套方法的所有日志中。
    • 您需要为此使用 LogContext.Push - 这可以在中间件中完成,或者通过在您的控制器等中执行 using (LogContext.Push("req",id)) 来完成。最好找到一个关于 Serilog LogContext 的好教程
    猜你喜欢
    • 2022-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    相关资源
    最近更新 更多