Forked from nblumhardt/JsonDocumentDestructuringPolicy.cs
Last active
March 12, 2025 16:24
-
-
Save beppemarazzi/b3292b207427481200676936a3553391 to your computer and use it in GitHub Desktop.
Properly serialize System.Text.Json documents with Serilog
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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