Serilog.Sinks.Logz.Io icon indicating copy to clipboard operation
Serilog.Sinks.Logz.Io copied to clipboard

Writing context object as JSON object rather than flattened fields

Open hardcodet opened this issue 11 months ago • 1 comments

I would like to log additional structured content that complements the logged message like this:

Logger
    .ForContext("payload", new {FooBar = "xxx", BarFoo = "yyy"}, true)
    .Warning("hello world");

This gives me some JSON similar to this with flattened properties and wrong casing:

{
  "message": "hello world",
  "level": "warning",
  ...
  "payload.FooBar": "xxx",
  "payload.BarFoo": "yyy"
}

Is there a setting or an easy way to override a formatter in order to have the payload logged like this (object with camel casing like the rest)?

{
  "message": "hello world",
  "level": "warning",
  ...
  "payload": {
    "fooBar": "xxx",
    "barFoo": "yyy"
  }
}

Thanks for your advice :)

hardcodet avatar Jan 06 '25 14:01 hardcodet

Update: Enrichers get me closer to the desired result - it appears only the camel casing is missing in your formatter. The property name itself is nicely converted to camel casing, but the serialized property isn't:

...
"payload": {
    "FooBar": "xxx",
    "BarFoo": "yyy"
},
...

I think the reason is that LogzIoSerializer doesn't configure camel casing in the serializer settings itself, but manually converts (only top-level) property names to lower case. This actually should be an easy fix:

// EXISTING SERIALIZER SETTINGS SETUP
SerializerSettings = new JsonSerializerSettings
{
    NullValueHandling = NullValueHandling.Ignore,
    ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
    Error = OnJsonError,
};

// FIX: ADD THE CONTRACT RESOLVER
if (fieldNaming == LogzIoTextFormatterFieldNaming.CamelCase)
{
    SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}

hardcodet avatar Jan 09 '25 21:01 hardcodet

You can achieve this in your own app doing this at the very begining:

        var serializer = new LogzIoSerializer(LogzIoTextFormatterFieldNaming.CamelCase)
        {
            SerializerSettings =
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            }
        };
        LogzIoSerializer.Instance = serializer;

mantasaudickas avatar Aug 06 '25 12:08 mantasaudickas