带有 json 格式化程序的控制台记录器不序列化对象

Console logger with json formatter does not serialize objects

我尝试使用没有任何第三方库的默认 .NET 核心日志记录工具。所以,问题。 带有 Json 格式化程序的控制台记录器是否支持 json 对象序列化?

我在应用程序设置中有以下配置

"Logging": {
    "Console": {
      "LogLevel": {
        "Default": "Debug",
        "System": "Information",
        "Microsoft": "Information",
        "Microsoft.Hosting.Lifetime": "Information"
      },
      "FormatterName": "json",
      "FormatterOptions": {
        "SingleLine": true,        
        "JsonWriterOptions": {
          "Indented": true
        }
      }
    }
  },

下面一行

logger.LogDebug("RequestId:{requestId} ResponseInfo: {@response} ", requestName, response);

生成带有 @response 对象的字符串表示的输出,在内部它仍然调用 ToString(),但是警告部分的文档说

The logging infrastructure itself already manages the serialization of log messages, so if you're to pass in a log message that is already serialized—it will be double serialized docs

这一点我认为它应该序列化对象。

我认为 build-in ILogger 不支持这个。这就是为什么我们可以 try the new System.Text.Json source generator.

The new System.Text.Json source generator can improve logging performance.


我想我们也可以选择third-party包,比如Serilog。那应该更容易做到这一点。