如何将我自己的属性添加到 Serilog 输出模板

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。

我做错了吗?或者有没有办法做到这一点?

如果要添加不属于消息模板的属性,则需要丰富日志上下文。这意味着添加 FromLogContext 丰富器,并以稍微不同的方式将您的属性添加到记录的事件中。

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");
}

您可以在 the documentation 中了解更多关于丰富的信息。

现在我不确定 Loggly。我以前从未使用过它。但是如果您使用的是 Seq(它来自 Serilog 的创建者并且最适合它),您甚至不需要修改输出模板。添加的属性将自动用于每个事件。

正如 Nicholas Blumhardt 通过评论指出的那样,如果您只需要一次性将 属性 添加到单个记录的事件中,您也可以这样做。当我有很多事件属性时,我有时会这样做,这些属性不一定需要显示在消息中,并且只适用于这个单一事件。

Log
   .ForContext("OrderNumber", orderNumber)
   .ForContext("UserId", user.Id)
   .Information("Order submitted");

您可以使用Enrich.WithProperty("ProperyName", "PropertyValue")

观看此 https://www.youtube.com/watch?v=OKITQsF6MNc&t=4831s 以了解 Asp.Net MVC 中的各种记录器

Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Information()
                .MinimumLevel.Override("Microsoft", Serilog.Events.LogEventLevel.Warning)
                .MinimumLevel.Override("System", Serilog.Events.LogEventLevel.Warning)
                .WriteTo.File(new Serilog.Formatting.Json.JsonFormatter(), "D:\Temp\Serilogs\structuredLog.json", rollingInterval: RollingInterval.Day, restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Information)
                .Enrich.FromLogContext()
                .Enrich.WithMachineName()
                .Enrich.WithProcessId()
                .Enrich.WithThreadId()
                .Enrich.WithProperty("ApplicationName", "Serilogs DemoApplication")
                .CreateLogger();