Add custom properties to Serilog

后端 未结 3 1159
名媛妹妹
名媛妹妹 2021-02-01 18:09

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 First         


        
3条回答
  •  猫巷女王i
    2021-02-01 18:42

    You can actually do this in a few different ways. In your case, the first way is probably the best:

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

    But you can also use the LogContext in other scenarios:

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

    Or, in the case where you want to log a "constant" property, you can add it like this:

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

    See Context and correlation – structured logging concepts in .NET (5) for more information.

提交回复
热议问题