【问题标题】:Add custom properties to Serilog向 Serilog 添加自定义属性
【发布时间】:2015-03-09 10:27:34
【问题描述】:

我在我的应用程序中使用带有 MS SQL Server 接收器的 Serilog。假设我已经定义了以下类...

public class Person
{
  public string FirstName { get; set; }
  public string LastName { get; set; }

  public DateTime BirthDate { get; set; }
  // ... 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 列中呈现?我想稍后在我的应用程序日志查看器的详细信息视图中输出它。

我基本上是在寻找类似于对象解构的行为,但没有将平面对象打印为日志消息的一部分。

【问题讨论】:

    标签: c# serilog


    【解决方案1】:

    这很简单:

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

    【讨论】:

    • 我明白了,这很简单。该方法是否还允许解构具有复杂类型的对象(例如 Person 类型的 Father 属性)?我对属性的值比ToString() 表示更感兴趣。
    • 绝对 - Log.ForContext("Father", father, destructureObjects: true) 这样做。
    • 完美!正是我想要的。我阅读了手册,但我一定以某种方式忽略了这一点。谢谢!
    【解决方案2】:

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

    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() 是我缺少的使基于属性的过滤工作的调用!
    【解决方案3】:

    如果您使用的是通用 Microsoft ILogger 界面,则可以使用 BeginScope;

    using (_logger.BeginScope(new Dictionary<string, object> { { "LogEventType", logEventType }, { "UserName",  userName } }))
    {
        _logger.LogInformation(message, args);
    }
    

    这里讨论; https://blog.rsuter.com/logging-with-ilogger-recommendations-and-best-practices/

    【讨论】:

      猜你喜欢
      • 2018-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-04
      • 2012-01-25
      相关资源
      最近更新 更多