首页 > 解决方案 > 如何在 Serilog 中记录消息模板的字段名称

问题描述

Serilog 中是否有任何设置告诉在使用输出模板时记录消息模板中的变量名称?

_logger.LogWarning(@"Role with Id {RoleId} not found", id);

我使用日志记录到文件并希望看到文件中记录的 RoleId 字段以及消息,因此我可以使用此字段进行过滤。我的 Serilog 设置看起来像

"Serilog": {
"MinimumLevel": {
  "Default": "Debug",
  "Override": {
    "Microsoft.EntityFrameworkCore.Storage.IRelationalCommandBuilderFactory": "Warning"
  }
},
"WriteTo": [
  {
    "Name": "File",
    "Args": {
      "path": "bin/Debug/netcoreapp2.0/Logs/log-.txt",
      "rollingInterval": "Day",
      "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss zzz} {Level:u3} {SourceContext} {Message:lj} {RequestId} {Properties} {NewLine} {Exception}"
      //"formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact"
    }
  }] 

}

我知道我可以使用LogContext.PushProperty("RoleId", id),但在我的情况下这不是一个选项以及使用CompactJsonFormatter.

标签: serilog

解决方案


我发现如果日志被写入文件并且$后面跟着字段(不是对象)(_logger.LogWarning("Role with Id {$RoleId} not found", id);) Serilog 将生成消息模板,带有 $sign 的字段名称和字段值。{Properties}也需要在outputTemplate.


推荐阅读