Skip to content

Json serialization exception for standard AspNetCore log message, which results in broken log messages #211

@saithis

Description

@saithis

We wanted to switch to ZLogger, but now immediatelly encountered this issue after trying it out:

ZLogger error: System.NotSupportedException: Serialization and deserialization of 'System.Reflection.RuntimeMethodInfo' instances is not supported. The unsupported member type is located on type 'System.Object'. Path: $.Metadata.
 ---> System.NotSupportedException: Serialization and deserialization of 'System.Reflection.RuntimeMethodInfo' instances is not supported.
   at System.Text.Json.Serialization.Converters.UnsupportedTypeConverter`1.Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWriteAsObject(Utf8JsonWriter writer, Object value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.Converters.IEnumerableDefaultConverter`2.OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonCollectionConverter`2.OnTryWrite(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.Metadata.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.WriteCore(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   --- End of inner exception stack trace ---
   at System.Text.Json.ThrowHelper.ThrowNotSupportedException(WriteStack& state, Exception innerException)
   at System.Text.Json.Serialization.JsonConverter`1.WriteCore(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.Metadata.JsonTypeInfo`1.Serialize(Utf8JsonWriter writer, T& rootValue, Object rootValueBoxed)
   at System.Text.Json.Serialization.Metadata.JsonTypeInfo`1.SerializeAsObject(Utf8JsonWriter writer, Object rootValue)
   at System.Text.Json.JsonSerializer.Serialize(Utf8JsonWriter writer, Object value, Type inputType, JsonSerializerOptions options)
   at ZLogger.LogStates.StringFormatterLogState`1.WriteJsonParameterKeyValues(Utf8JsonWriter jsonWriter, JsonSerializerOptions jsonSerializerOptions, IKeyNameMutator keyNameMutator)
   at ZLogger.ZLoggerEntry`1.WriteJsonParameterKeyValues(Utf8JsonWriter jsonWriter, JsonSerializerOptions jsonSerializerOptions, IKeyNameMutator keyNameMutator)
   at ZLogger.Formatters.SystemTextJsonZLoggerFormatter.FormatLogEntry(IBufferWriter`1 writer, IZLoggerEntry entry)
   at ZLogger.ZLoggerEntry`1.FormatUtf8(IBufferWriter`1 writer, IZLoggerFormatter formatter)
   at ZLogger.AsyncStreamLineMessageWriter.WriteLoop()
{
  "Timestamp": "2025-08-06T09:50:41.6766875+02:00",
  "LogLevel": "Information",
  "Category": "Microsoft.AspNetCore.Routing.EndpointMiddleware",
  "Message": "Executed endpoint 'HTTP: POST /validation/body => Handle'",
  "SpanId": "926ae9e59ec8abfc",
  "TraceId": "ececed91e60b6005911ce384052b4b56",
  "ParentId": "0000000000000000",
  "ConnectionId": "0HNEKNNOFC647",
  "RequestId": "0HNEKNNOFC647:00000001",
  "RequestPath": "/validation/body",
  "User": "anonymous"{ // <---- here ------------------------------
  "Timestamp": "2025-08-06T09:50:41.6820922+02:00",
  "LogLevel": "Information",
  "Category": "Microsoft.AspNetCore.Hosting.Diagnostics",
  "Message": "Request finished HTTP/1.1 POST http://localhost:5097/validation/body - 400 - application/problem+json 318.6568ms",
  "SpanId": "926ae9e59ec8abfc",
  "TraceId": "ececed91e60b6005911ce384052b4b56",
  "ParentId": "0000000000000000",
  "ConnectionId": "0HNEKNNOFC647",
  "RequestId": "0HNEKNNOFC647:00000001",
  "RequestPath": "/validation/body",
  "ElapsedMilliseconds": 318.6568,
  "StatusCode": 400,
  "ContentType": "application/problem+json",
  "ContentLength": null,
  "Protocol": "HTTP/1.1",
  "Method": "POST",
  "Scheme": "http",
  "Host": "localhost:5097",
  "PathBase": "",
  "Path": "/validation/body",
  "QueryString": ""
}

It just starts with the next log message without finishing the first one.
But this is just a standard asp net core log message, so I expected ZLogger to be able to handle that.

Our ZLogger config is like this:

        hostBuilder.ConfigureLogging(builder => builder
            .ClearProviders()
            .AddZLoggerConsole(o =>
            {
                o.IncludeScopes = true;
                o.InternalErrorLogger = ex => Console.Error.WriteLine($"ZLogger error: {ex}");
                o.UseJsonFormatter(formatter =>
                {
                    formatter.JsonSerializerOptions.WriteIndented = true;
                });
            }));

And since it is exactly after the User property each time, maybe this is also important:

app.Use(async (ctx, next) => 
{
    var logger = ctx.RequestServices.GetRequiredService<ILogger<Program>>();
    using var loggerScope = logger.BeginScope(new Dictionary<string, object>
    {
        {"User", ctx.User.FindFirst("sub")?.Value ?? "anonymous" },
    });
    await next();
});

Metadata

Metadata

Assignees

No one assigned

    Labels

    stalestale not updated issue & pr

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions