.Net Core 1.1 not serializing object while logging

3.4k Views Asked by At

I have ASP.NET Core 1.1 application and i am using Serilog for logging. I want to log DTO object by preserving its structure.

So If i directly use Serilog.Log to log the DTO, like below

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

Then Serilog serializes the DTO and log it as expected.

However i am injecting Microsoft.Extension.Logging.ILogger into controller. I thought it will use configured logger for logging and that will serialize the object while logging, but its not. It only logs type name of the object.

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

There are 1 best solutions below

0
On

I found it. My mistake

in Startup.cs in Configure method i was only adding Serilog for non development environment and i was testing locally with ASPNETCORE_ENVIRONMENT = Development.

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

i removed if condition and it worked. So _logger.LogInformation("DTO {@dto}",dto); works