c# - .Net Core 1.1 在记录时不序列化对象

标签 c# asp.net-core .net-core serilog semantic-logging

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

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

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

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

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

        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"        
      }
    ]
  },

最佳答案

我找到了。我的错误

在配置方法中的Startup.cs中,我只为非开发环境添加了Serilog,并且我正在使用 ASPNETCORE_ENVIRONMENT = Development 进行本地测试。

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

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

关于c# - .Net Core 1.1 在记录时不序列化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54834986/

相关文章:

c# - 如何使用 native C++的COM实现C#的接口(interface)?

c# - 带有 AsyncLocal 与 Scope 服务的单例

c# - 十进制数字逗号样式

c# - 使用 Roslyn-CTP 的单个右括号的奇怪解析行为

mysql - Entity Framework 核心与字段列表中的mysql未知列

c# - 模型状态错误 : The value 'null' is not valid for nullable field

asp.net-core - 核心推送通知

c# - 我的验证器都不起作用

c# - .NET 中如何实现 "Event"对象?

.net-assembly - 如何将 DNU WRAP 用于不在 ASP.Net 项目解决方案中的项目