Skip to content

Commit 446034b

Browse files
author
Bart Koelman
committed
Switched to STJ in rendering CLR objects as part of tracing. STJ properly handles self-referencing EF Core objects when enabling reference tracking, as opposed to Newtonsoft.
1 parent bb83e32 commit 446034b

File tree

1 file changed

+16
-7
lines changed

1 file changed

+16
-7
lines changed

src/JsonApiDotNetCore/Middleware/TraceLogWriter.cs

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,24 @@
22
using System.Reflection;
33
using System.Runtime.CompilerServices;
44
using System.Text;
5+
using System.Text.Encodings.Web;
6+
using System.Text.Json;
7+
using System.Text.Json.Serialization;
58
using Microsoft.Extensions.Logging;
6-
using Newtonsoft.Json;
79

810
namespace JsonApiDotNetCore.Middleware
911
{
10-
internal sealed class TraceLogWriter<T>
12+
internal abstract class TraceLogWriter
13+
{
14+
protected static readonly JsonSerializerOptions SerializerOptions = new()
15+
{
16+
WriteIndented = true,
17+
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
18+
ReferenceHandler = ReferenceHandler.Preserve
19+
};
20+
}
21+
22+
internal sealed class TraceLogWriter<T> : TraceLogWriter
1123
{
1224
private readonly ILogger _logger;
1325

@@ -126,12 +138,9 @@ private static string SerializeObject(object value)
126138
{
127139
try
128140
{
129-
// It turns out setting ReferenceLoopHandling to something other than Error only takes longer to fail.
130-
// This is because Newtonsoft.Json always tries to serialize the first element in a graph. And with
131-
// EF Core models, that one is often recursive, resulting in either StackOverflowException or OutOfMemoryException.
132-
return JsonConvert.SerializeObject(value, Formatting.Indented);
141+
return JsonSerializer.Serialize(value, SerializerOptions);
133142
}
134-
catch (JsonSerializationException)
143+
catch (JsonException)
135144
{
136145
// Never crash as a result of logging, this is best-effort only.
137146
return "object";

0 commit comments

Comments
 (0)