Ste*_*ven 4 c# logging serilog
我有一个小应用程序正在从服务总线接收消息,该服务总线可以为不同的用户发送几种不同类型的事件.根据事件的类型,调用不同的函数.我正在记录这些功能中的每一个.
我目前有这个:
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");
Run Code Online (Sandbox Code Playgroud)
这很好,但是因为对于这个应用程序,每个日志都会在日志中包含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"});
Run Code Online (Sandbox Code Playgroud)
这些都不起作用,它输出的只是我的消息,它不会通过我传入其中的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");
}
Run Code Online (Sandbox Code Playgroud)
您可以在文档中了解有关丰富的更多信息.
现在我不确定Loggly.我以前从未使用过它.但是如果你使用的是Seq(它来自Serilog的创建者并且最适合它),你甚至不需要修改输出模板.添加的属性将自动用于每个事件.
正如Nicholas Blumhardt通过评论指出的那样,如果你只需要一次性地为一个记录的事件添加一个属性,你也可以这样做.当有很多属性用于不一定需要在消息中显示的事件时,我有时会这样做,并且仅适用于此单个事件.
Log
.ForContext("OrderNumber", orderNumber)
.ForContext("UserId", user.Id)
.Information("Order submitted");
Run Code Online (Sandbox Code Playgroud)