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);
            }

        }

启动.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();

}

应用设置.json

"Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Information"
    }
  },
  "Serilog": {
    "WriteTo": [
      {
        "Name": "ColoredConsole"        
      }
    ]
  },
4

1 回答 1

1

我找到了。我的错

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

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

我删除了如果条件并且它有效。所以_logger.LogInformation("DTO {@dto}",dto);有效

于 2019-02-22T22:40:42.447 回答