消息模板中未使用的属性的 Serilog 字段名称

Serilog field names for properties not used in message template

我正在测试 Serilog,我遇到了一些字段名称问题。

我想添加一个日志条目,其中一个字段包含在消息模板中,而其他字段只是存储在日志中以供查询。

我想做这样简单的事情:

logger.Debug("Recalculation performed for operation {OperationId}", 
                operationId, operationTypeId, otherId, anotherId);

但这会导致字段名称未被赋予友好名称,因为它们不在消息模板中:

{
   "@timestamp":"2016-10-20T16:57:02.0623798+01:00",
   "level":"Debug",
   "messageTemplate":"Recalculation performed for operation {OperationId}",
   "fields":{  
      "OperationId":1024,
      "__1":16,
      "__2":32,
      "__3":256,
      "SourceContext":"SerilogTest.Worker"
   }
}

我知道我可以将所有字段放入 class 并使用 ForContext 方法将它们包含在日志条目中:

internal class OperationData
{
    public int OperationId { get; set; }

    public int OperationTypeId { get; set; }

    public int OtherId { get; set; }

    public int AnotherId { get; set; }
}

var operationData = new OperationData
                {
                    OperationId = 1024,
                    OperationTypeId = 16,
                    OtherId = 32,
                    AnotherId = 256
                };

var operationLogger = logger.ForContext("OperationData", 
                        operationData, destructureObjects: true);
operationLogger.Debug("Recalculation performed for operation {OperationId}",
                         operationData.OperationId);

这种让我得到我正在寻找的结果:

{
   "@timestamp":"2016-10-20T18:00:35.4956991+01:00",
   "level":"Debug",
   "messageTemplate":"Recalculation performed for operation {OperationId}",
   "fields":{  
      "OperationId":1024,
      "OperationData":{  
         "_typeTag":"RecalulationResult",
         "OperationId":1024,
         "OperationTypeId":16,
         "OtherId":32,
         "AnotherId":256
      },
      "SourceContext":"SerilogTest.Worker"
   }
}

但是,为了拥有友好的字段名称似乎需要付出很多努力。我必须创建一个新的记录器实例,有一个类型来包含日志消息的所有相关字段,然后执行日志。有没有比这更简单的字段命名方式?

匿名类型用更少的代码实现上面的功能:

logger
    .ForContext("Operation", new {operationTypeId, otherId, anotherId}, true)
    .Debug("Recalculation performed for operation {OperationId}", operationId);

或者通过在事件中包含所有内容:

logger.Debug("Recalculation performed for operation {@Operation}", new {
        Id = operationId, TypeId = operationTypeId, OtherId = otherId, 
        AnotherId = anotherId
    });

如果您发现有很多邮件要包含相同的属性,最好将它们推送到 LogContext:

using (LogContext.PushProperty("OperationId", operationId))
{
    logger.Debug("Recalculation performed");

    // ...etc...

    logger.Debug("Something else");
}

在这种情况下,两个事件都会有一个 OperationId 与之关联。您可以将多个属性推送到日志上下文中。只需确保将 Enrich.FromLogContext() 添加到 LoggerConfiguration 即可使用此样式。