【问题标题】:.NET Core Serilog Add username to logs via enrichment or middleware.NET Core Serilog 通过扩充或中间件将用户名添加到日志
【发布时间】:2018-10-03 15:52:36
【问题描述】:

我正在尝试将用户名添加到我的日志中。文档显示了这一点:

class ThreadIdEnricher : ILogEventEnricher
{
    public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
    {
        logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty(
                "ThreadId", Thread.CurrentThread.ManagedThreadId));
    }
}

但是,我在其他地方读到我需要使用中间件将用户名添加到日志中。

这是我目前所拥有的:

获取当前用户用户名的中间件

public class UserNameEnricher 
{
    private readonly RequestDelegate next;

    public UserNameEnricher(RequestDelegate next)
    {
        this.next = next;
    }

    public Task Invoke(HttpContext context)
    {
        LogContext.PushProperty("UserName", context.User.Identity.Name);

        return next(context);
    }
}

Startup.cs

app.UseAuthentication();
app.UseMiddleware<UserNameEnricher>();

程序.cs

Log.Logger = new LoggerConfiguration()
   .ReadFrom.Configuration(Configuration)
   .Filter.ByExcluding(Matching.FromSource("Microsoft"))
   .Filter.ByExcluding(Matching.FromSource("System"))
   .Enrich.FromLogContext()
   .CreateLogger();

但是,尽管进行了所有这些配置,用户名仍然没有出现。我错过了什么?

Serilog 配置:

"Serilog": {
    "MinimumLevel": "Information",
    "Override": {
      "Microsoft": "Critical",
    },
    "WriteTo": [
      {
        "Name": "MSSqlServer",
        "Args": {
          "connectionString": "Server=.\\SQLEXPRESS;Database=App-7661DEE4-C53F-4E49-B140-2AFAA2C85927;Integrated Security=True;Trusted_Connection=True;MultipleActiveResultSets=true;",
          "schemaName": "App",
          "tableName": "EventLogs"
        }
      }
    ]
  },

【问题讨论】:

  • 是的,这些都不适合我。
  • 您可能需要在格式字符串的某处使用{Properties}?您是否尝试过设置断点并检查流经和/或发送到始终具有它们的 Seq 的日志事件之一。 (见getseq.net
  • 如何设置属性?
  • Properties 是已添加但未在消息中使用的属性的全部标记 - 再次,强烈建议设置 Seq 以进行本地测试以帮助您学习这些内容(有关格式化消息的文档将比我更好地向你解释属性)

标签: c# asp.net asp.net-core serilog


【解决方案1】:

为了让它工作,你需要指定outputTemplate

事件的属性,包括使用扩充器附加的属性,也可以出现在输出模板中。

Output templates

这是一个用于RollingFile 的演示代码。

var output = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message} {ActionName} {UserName} {NewLine}{Exception}";

        Log.Logger = new LoggerConfiguration()
               .Enrich.FromLogContext() // Populates a 'User' property on every log entry
               .WriteTo.RollingFile("Logs/app-{Date}.txt",outputTemplate: output)
               .CreateLogger();

注意

输出中的{UserName} 应该映射到LogContext.PushProperty("UserName", context.User.Identity.Name); 中的UserName

更新:

appsetting.json配置

  "Serilog": {
"MinimumLevel": "Information",
"Override": {
  "Microsoft": "Critical"
},
"WriteTo": [
  {
    "Name": "RollingFile",
    "Args": {
      "pathFormat": "Logs/app-{Date}.txt",
      "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message} {UserName} {ActionName}  {NewLine} {Exception}"
    }
  }
]
   }

【讨论】:

  • 嗨@Tao Zhou,这是否意味着我必须用appsettings.json中的那个覆盖当前的输出模板?
  • @JianYA 是的,你需要指定在哪里添加UserName
猜你喜欢
  • 2018-05-14
  • 2017-02-15
  • 2018-12-18
  • 2021-07-21
  • 1970-01-01
  • 1970-01-01
  • 2020-08-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多