向Serilog添加自定义属性

43

我在我的应用程序中使用Serilog和MS SQL Server sink。假设我已经定义了以下类...

public class Person
{
  public string FirstName { getset; }
  public string LastName { getset; }

  public DateTime BirthDate { getset; }
  // ... more properties
}

...并创建了一个实例:

var person = new Person
{
    FirstName = "John",
    LastName = "Doe",
    BirthDate = DateTime.UtcNow.AddYears(-25)
};

我已在我的代码中放置了以下日志调用:

Log.Information("New user: {FirstName:l} {LastName:l}",
    person.FirstName, person.LastName);

是否有可能在不将BirthDate属性添加到消息模板中的情况下,也记录该属性,以便在Properties XML列中呈现?我希望稍后可以在应用程序日志查看器的详细视图中输出它。

我基本上正在寻找类似于对象解构的行为,但不会将平面对象作为日志消息的一部分打印出来。

3个回答

51

这很简单:

Log.ForContext("BirthDate", person.BirthDate)
   .Information("New user: {FirstName:l} {LastName:l}",
                           person.FirstName, person.LastName);

我明白了,这很简单。那个方法是否也允许解构具有复杂类型的对象(例如类型为PersonFather属性)?我更关心属性的值而不是ToString()表示。 - Marius Schulz
10
没问题 - Log.ForContext("Father", father, destructureObjects: true) 就是这个意思。 - Nicholas Blumhardt
太好了!正是我想要的。我看过手册,但可能不小心忽略了那部分。谢谢! - Marius Schulz

35

你实际上可以用几种不同的方式来做到这一点。在你的情况下,第一种方式可能是最好的:

Log.ForContext("BirthDate", person.BirthDate)
    .Information("New user: {FirstName:l} {LastName:l}",
        person.FirstName, person.LastName);

但您也可以在其他场景中使用LogContext

Log.Logger = new LoggerConfiguration()
    // Enrich all log entries with properties from LogContext
    .Enrich.FromLogContext();

using (LogContext.PushProperty("BirthDate", person.BirthDate))
{
    Log.Information("New user: {FirstName:l} {LastName:l}",
        person.FirstName, person.LastName);
}

或者,在您想记录“常量”属性的情况下,您可以像这样添加:

Log.Logger = new LoggerConfiguration()
    // Enrich all log entries with property
    .Enrich.WithProperty("Application", "My Application");

请参阅 Context and correlation – structured logging concepts in .NET (5) 以获取更多信息。


".Enrich.FromLogContext()"是我缺少的调用,使我的基于属性的过滤工作!" - Alexis Leclerc

17

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接