Skip to content

Instantly share code, notes, and snippets.

@nblumhardt
Created August 7, 2019 08:13
Show Gist options
  • Save nblumhardt/8aea89e86663829170d08aa573bd0f49 to your computer and use it in GitHub Desktop.
Save nblumhardt/8aea89e86663829170d08aa573bd0f49 to your computer and use it in GitHub Desktop.
Properly serialize System.Text.Json documents with Serilog
using System;
using System.Linq;
using System.Text.Json;
using Serilog.Core;
using Serilog.Events;
class JsonDocumentDestructuringPolicy : IDestructuringPolicy
{
public bool TryDestructure(object value, ILogEventPropertyValueFactory _, out LogEventPropertyValue result)
{
if (!(value is JsonDocument jdoc))
{
result = null;
return false;
}
result = Destructure(jdoc.RootElement);
return true;
}
static LogEventPropertyValue Destructure(in JsonElement jel)
{
switch (jel.ValueKind)
{
case JsonValueKind.Array:
return new SequenceValue(jel.EnumerateArray().Select(ae => Destructure(in ae)));
case JsonValueKind.False:
return new ScalarValue(false);
case JsonValueKind.True:
return new ScalarValue(true);
case JsonValueKind.Null:
case JsonValueKind.Undefined:
return new ScalarValue(null);
case JsonValueKind.Number:
return new ScalarValue(jel.GetDecimal());
case JsonValueKind.String:
return new ScalarValue(jel.GetString());
case JsonValueKind.Object:
return new StructureValue(jel.EnumerateObject().Select(jp => new LogEventProperty(jp.Name, Destructure(jp.Value))));
default:
throw new ArgumentException("Unrecognized value kind " + jel.ValueKind + ".");
}
}
}
@beppemarazzi
Copy link

i forked this with a very little change to manage also JsonElement and accomodate my use case. https://gist.github.com/beppemarazzi/b3292b207427481200676936a3553391 feel free to pull it back if you want...

    public bool TryDestructure(object value, ILogEventPropertyValueFactory _, out LogEventPropertyValue result)
    {
        switch (value)
        {
            case JsonDocument jdoc:
                result = Destructure(jdoc.RootElement);
                return true;
            case JsonElement jel:
                result = Destructure(jel);
                return true;
        }

        result = null;
        return false;
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment