[英]How to add my own properties to Serilog output template
我有一個小應用程序正在從服務總線接收消息,該服務總線可以為不同的用戶發送幾種不同類型的事件。 根據事件的類型,調用不同的函數。 我正在記錄這些功能中的每一個。
我目前有這個:
var logger = new LoggerConfiguration()
.MinimumLevel.Information()
.WriteTo.Console(outputTemplate:
"[{Timestamp:HH:mm:ss} {Level:u3}] {Message}{NewLine}{Exception}")
.WriteTo.Loggly()
.CreateLogger();
...
// logging an event
Log.Information("{UserId} {Event} - Here is my message", "123", "Test Event");
這很好,但是因為對於這個應用程序,每個日志都會在日志中包含UserId和Event數據,我想我可以將它們添加到我的輸出模板中,以使我的日志代碼更加清晰。 所以我試過這個:
var logger = new LoggerConfiguration()
.MinimumLevel.Information()
.WriteTo.Console(outputTemplate:
"[{Timestamp:HH:mm:ss} {Level:u3}] {UserId} {Event} - {Message}{NewLine}{Exception}")
.WriteTo.Loggly()
.CreateLogger();
...
// logging an event
Log.Information("Here is my message", "123", "Test Event");
Log.Information("Here is my message", new { UserId = "123", Event = "Test Event"});
這些都不起作用,它輸出的只是我的消息,它不會通過我傳入其中的UserId或Event。
我做錯了嗎? 或者甚至有辦法做到這一點?
如果要添加不屬於消息模板的屬性,則需要豐富日志上下文。 這意味着添加日志上下文更豐富,並將您的屬性添加到您記錄的事件有點不同。
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.MinimumLevel.Information()
.WriteTo.Console(outputTemplate:
"[{Timestamp:HH:mm:ss} {Level:u3}] {UserId} {Event} - {Message}{NewLine}{Exception}")
.CreateLogger();
using (LogContext.PushProperty("UserId", "123"))
using (LogContext.PushProperty("Event", "Test Event"))
{
Log.Information("Here is my message about order {OrderNumber}", 567);
Log.Information("Here is my message about product {ProductId}", "SomeProduct");
}
您可以在文檔中了解有關豐富的更多信息。
現在我不確定Loggly。 我以前從未使用過它。 但是如果你使用的是Seq(它來自Serilog的創建者並且最適合它),你甚至不需要修改輸出模板。 添加的屬性將自動用於每個事件。
正如Nicholas Blumhardt通過評論指出的那樣,如果你只需要一次性地為一個記錄的事件添加一個屬性,你也可以這樣做。 當有很多屬性用於不一定需要在消息中顯示的事件時,我有時會這樣做,並且僅適用於此單個事件。
Log
.ForContext("OrderNumber", orderNumber)
.ForContext("UserId", user.Id)
.Information("Order {OrderNumber} submitted", order.OrderNumber);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.