Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save beppemarazzi/b3292b207427481200676936a3553391 to your computer and use it in GitHub Desktop.
Save beppemarazzi/b3292b207427481200676936a3553391 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)
{
switch (value)
{
case JsonDocument jdoc:
result = Destructure(jdoc.RootElement);
return true;
case JsonElement jel:
result = Destructure(jel);
return true;
}
result = null;
return false;
}
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 + ".");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment