.Net Core 1.1在记录时不会序列化对象

问题描述 投票:0回答:1

我有ASP.NET Core 1.1应用程序,我使用Serilog进行日志记录。我想通过保留其结构来记录DTO对象。

所以,如果我直接使用Serilog.Log来记录DTO,如下所示

Serilog.Log.Information("Processing {@DTO}", dto);

然后Serilog序列化DTO并按预期记录它。

然而,我正在注入Microsoft.Extension.Logging.ILogger控制器。我认为它将使用配置的记录器进行日志记录,并且会在记录时序列化对象,但事实并非如此。它只记录对象的类型名称。

        public class HomeController
        {
            private readonly Microsoft.Extensions.Logging.ILogger _logger = null

            public HomeController(Microsoft.Extensions.Logging.ILogger logger)
            {
               _logger = logger;
            }           

            public asyc IActionResult Index()
            {               
                var dto = GetDTO();

                //did not work
                _logger.LogInformation("DTO {dto}",dto);

                //did not work
                _logger.LogInformation("DTO {@dto}",dto);

                //worked when i use serilog directly
                Serilog.Log.Information("DTO {@dto}",dto);

                //did not work
                Serilog.Log.Information("DTO {dto}",dto);
            }

        }

Startup.cs

    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();

        if (env.IsDevelopment())
        {
            // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
            builder.AddApplicationInsightsSettings(developerMode: true);
        }

        Configuration = builder.Build();

        Log.Logger = new LoggerConfiguration()
        .ReadFrom.Configuration(Configuration)
        .CreateLogger();

}

appsettings.json

"Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Information"
    }
  },
  "Serilog": {
    "WriteTo": [
      {
        "Name": "ColoredConsole"        
      }
    ]
  },
c# asp.net-core .net-core serilog semantic-logging
1个回答
0
投票

我找到了。我的错

Startup.cs的配置方法中我只为非开发环境添加Serilog,我在本地测试ASPNETCORE_ENVIRONMENT =开发。

if(!env.IsDevelopment())
{
   loggerFactory.AddSerilog();
}

我删除了条件,它工作。所以_logger.LogInformation("DTO {@dto}",dto);工作

© www.soinside.com 2019 - 2024. All rights reserved.