[英]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"
}
}
我知道我可以將所有字段放入一個類中,並使用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
即可使用此樣式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.