Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Console logger with json formatter does not serialize objects

I try to use default .NET core logging tools without any third party libs. So, question. Does console logger with Json formatter support json serialization of objects?

I have the following config in appsettings

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

The following line

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

produces the output with string representation of @response object, internally it still invokes ToString(), but docs in Caution section says that

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

And this point me that it should serialize object.

like image 850
user3529134 Avatar asked Sep 17 '25 02:09

user3529134


1 Answers

I think the build-in ILogger don't support this. That's why we can try the new System.Text.Json source generator.

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


I think we also can choose third-party package, like Serilog. That should be more easy to do this.

like image 98
Jason Pan Avatar answered Sep 19 '25 20:09

Jason Pan