Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Serilog destructure complex objects passed to BeginScope?

I'm using Serilog.Extensions.Logging and outputting to console with this outputTemplate:

"{Timestamp:HH:mm} [{Level:u3}] {Message} {Properties:j} {NewLine}"

What I would like to see, is that complex objects set via BeginScope get destructured into Properties. Instead, it seems, the type name is used.

var data = new Data { Id = 42, Name = "Hitchhiker" };
using (logger.BeginScope(new Dictionary<string, object> { { "Data", data } }))
{
    logger.LogInformation("Hello world!");
}

The result is:

10:40 [INF] Hello world! {"SourceContext": "ConsoleApp3.Program", "Data": "ConsoleApp3.Data"}

What I want is:

10:40 [INF] Hello world! {"SourceContext": "ConsoleApp3.Program", "Data": { "Id" = 42, "Name" = "Hitchhiker"} }

Am I missing a configuration setting, or is this simply not possible?

edit

Just noticed that this can be accomplished by vanilla Serilog:

var dataLogger = logger.ForContext("Data", data, true);

Here the last parameter informs Serilog that it should destructure the complex type.

like image 951
AroglDarthu Avatar asked Jan 15 '20 10:01

AroglDarthu


1 Answers

The complex type will get destructured if the key is prefixed with an @ character. So:

using (logger.BeginScope(new Dictionary<string, object> { { "@Data", data } }))

does the trick :-)

like image 145
AroglDarthu Avatar answered Sep 19 '22 12:09

AroglDarthu