asp.net-core - 带有 json 格式化程序的控制台记录器不会序列化对象

标签 asp.net-core logging .net-5

我尝试使用默认的 .NET Core 日志记录工具,而不使用任何第三方库。那么,问题。 带有 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

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

最佳答案

我认为内置的ILogger不支持这一点。这就是为什么我们可以 try the new System.Text.Json source generator .

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


我想我们也可以选择第三方包,比如Serilog。这样做应该更容易。

关于asp.net-core - 带有 json 格式化程序的控制台记录器不会序列化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71145688/

相关文章:

c# - ASP.NET _ViewStart.cshtml - 获取请求

java - 如何使用带有 log4j2 的 Java 日志记录来正确管理使用插件创建的日志文件的生命周期

C# HttpClient 不处理 304/307 重定向

c# - NET 5 和 EF : how to use AddPooledDbContextFactory in liu of DbContext in services

c# - 子范围中每个请求范围的 Asp.net Core 服务

asp.net-core - ASP.NET Core 3.x Endpoints路由中,如何指定域名?

grails - Grails:如何记录wslite SOAP消息?

performance - ILogger 到 blob 存储速度很慢

c# - 为什么在 .NET 5 中指定循环枚举值时,枚举的顺序很重要?

c# - 如何动态定义匿名对象属性?