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

时间:2016-10-20 17:26:41

标签: c# logging serilog

我正在测试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"
   }
}

我知道我可以将所有字段放入一个类中,并使用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"
   }
}

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

1 个答案:

答案 0 :(得分:2)

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

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即可使用此样式。