Skip to content

Commit

Permalink
Switched to STJ in rendering CLR objects as part of tracing. STJ prop…
Browse files Browse the repository at this point in the history
…erly handles self-referencing EF Core objects when enabling reference tracking, as opposed to Newtonsoft.
  • Loading branch information
Bart Koelman committed Sep 7, 2021
1 parent bb83e32 commit 446034b
Showing 1 changed file with 16 additions and 7 deletions.
23 changes: 16 additions & 7 deletions src/JsonApiDotNetCore/Middleware/TraceLogWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,24 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace JsonApiDotNetCore.Middleware
{
internal sealed class TraceLogWriter<T>
internal abstract class TraceLogWriter
{
protected static readonly JsonSerializerOptions SerializerOptions = new()
{
WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
ReferenceHandler = ReferenceHandler.Preserve
};
}

internal sealed class TraceLogWriter<T> : TraceLogWriter
{
private readonly ILogger _logger;

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

0 comments on commit 446034b

Please sign in to comment.