Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add custom properties to Serilog

Tags:

c#

serilog

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

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.

like image 508
Marius Schulz Avatar asked Jan 11 '15 15:01

Marius Schulz


2 Answers

This is as simple as:

Log.ForContext("BirthDate", person.BirthDate)    .Information("New user: {FirstName:l} {LastName:l}",                            person.FirstName, person.LastName); 
like image 181
Nicholas Blumhardt Avatar answered Sep 21 '22 19:09

Nicholas Blumhardt


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.

like image 34
Christian Davén Avatar answered Sep 19 '22 19:09

Christian Davén