Can Serilog destructure complex objects passed to BeginScope?
Asked Answered
I

1

11

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.

Irradiance answered 15/1, 2020 at 10:4 Comment(0)
I
18

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

Irradiance answered 15/1, 2020 at 14:1 Comment(1)
Is there no other way to configure that globally? This kinda is leaking internals, cause if you'd switch logger implementation, you'd have to change these too everywhere right?Therapeutics

© 2022 - 2024 — McMap. All rights reserved.