向 Serilog 添加自定义属性 [英] Add custom properties to Serilog
问题描述
我在我的应用程序中使用 Serilog 和 MS SQL Server 接收器.假设我已经定义了以下类...
I'm using Serilog with an MS SQL Server sink in my application. Let's assume I have defined the following class ...
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime BirthDate { get; set; }
// ... more properties
}
...并创建了一个实例:
... and created an instance:
var person = new Person
{
FirstName = "John",
LastName = "Doe",
BirthDate = DateTime.UtcNow.AddYears(-25)
};
我在我的代码中放置了以下日志调用:
I have placed the following log call in my code:
Log.Information("New user: {FirstName:l} {LastName:l}",
person.FirstName, person.LastName);
是否也可以记录 BirthDate
属性而不将其添加到消息模板,以便它在 Properties
XML 列中呈现?我想稍后在我的应用程序日志查看器的详细信息视图中输出它.
Is it possible to also log the BirthDate
property without adding it to the message template so that it's rendered within the Properties
XML column? I'd like to output it later in a details view of my application's log viewer.
我基本上是在寻找类似于对象解构的行为,但没有将平面对象打印为日志消息的一部分.
I'm basically looking for a behavior similar to the object destructuring, but without printing the flat object as part of the log message.
推荐答案
这很简单:
Log.ForContext("BirthDate", person.BirthDate)
.Information("New user: {FirstName:l} {LastName:l}",
person.FirstName, person.LastName);
这篇关于向 Serilog 添加自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!