Created
August 7, 2019 08:13
-
-
Save nblumhardt/8aea89e86663829170d08aa573bd0f49 to your computer and use it in GitHub Desktop.
Properly serialize System.Text.Json documents with Serilog
This file contains hidden or 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) | |
{ | |
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 + "."); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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...