【问题标题】:serilog push property using multiple timesserilog 推送属性多次使用
【发布时间】:2022-04-01 18:39:14
【问题描述】:

我有一个根据这篇博文https://blog.datalust.co/smart-logging-middleware-for-asp-net-core/ 实现的 serilog 中间件类

如果我想多次使用 LogContext.PushProperty 在我的日志中推送各种信息,我只需将以下代码放入我的 Invoke 方法中:

LogContext.PushProperty("Address", httpContext.Connection.RemoteIpAddress);
LogContext.PushProperty("Username", httpContext.User.Identity.IsAuthenticated ? httpContext.User.Identity.Name : null);

LogContext.PushProperty 的文档只显示了添加一个属性并说要使用 using 块还是我需要执行以下操作:

using (LogContext.PushProperty("Address", 
httpContext.Connection.RemoteIpAddress))
        using (LogContext.PushProperty("Username", httpContext.User.Identity.IsAuthenticated ? httpContext.User.Identity.Name : null))
    {  //rest of invoke method here }

【问题讨论】:

  • 您的使用语法是正确的。

标签: asp.net-core serilog


【解决方案1】:

这是一个例子https://github.com/serilog/serilog/wiki/Enrichment

log.Information("No contextual properties");

using (LogContext.PushProperty("A", 1))
{
    log.Information("Carries property A = 1");

    using (LogContext.PushProperty("A", 2))
    using (LogContext.PushProperty("B", 1))
    {
        log.Information("Carries A = 2 and B = 1");
    }

    log.Information("Carries property A = 1, again");
}

只需使用多人游戏

    using (LogContext.PushProperty("A", 2))
    using (LogContext.PushProperty("B", 1)) 
    { ... }

【讨论】:

    【解决方案2】:

    LogContext 可以使用 Push 方法:

    ILogEventEnricher[] enrichers = 
    {
        new PropertyEnricher("Address", httpContext.Connection.RemoteIpAddress),
        new PropertyEnricher("Username", httpContext.User.Identity.IsAuthenticated ? httpContext.User.Identity.Name : null),
    };
    
    using (LogContext.Push(enrichers))
    {
        // your code...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多