Serilog ReadFrom Configuration

j-hurst picture j-hurst · Aug 31, 2018 · Viewed 11k times · Source

I am attempting to load my Serilog configuration from appsettings.json using the Serilog.Settings.Configuration prerelease NuGet package. However when I load it using Configuration.GetSection, the value continues to come back as null.

Here is what I have in my Program.cs file:

    return WebHost.CreateDefaultBuilder(args)
    .UseStartup<Startup>()
    .ConfigureLogging(
        (hostingContext, loggingBuilder) =>
        {
            loggingBuilder.ClearProviders();
            loggingBuilder.AddSerilog(
                new LoggerConfiguration()
                    .ReadFrom.ConfigurationSection(hostingContext.Configuration.GetSection("Serilog"))
                    .CreateLogger()
            );
        }
    );

Here is what I have in my appsettings.json file:

    {
    "Serilog": {
        "Using": [ "Serilog.Sinks.MSSqlServer" ],
        "MinimumLevel": {
            "Default": "Verbose",
            "Override": {
                "Microsoft": "Verbose",
                "System": "Verbose",
                "Microsoft.AspNetCore.Authentication": "Verbose"
            }
        },
        "WriteTo": [
            {
                "Name": "MSSqlServer",
                "Args": {
                    "connectionString": "*my_connectionString*",
                    "tableName": "ErrorLog"
                }
            }
        ]
    }}

NuGet packages installed:

  • Microsoft.AspNetCore.App v2.1.1
  • Serilog v2.7.1
  • Serilog.AspNetCore v2.1.1
  • Serilog.Extensions.Logging v2.0.2
  • Serilog.Settings.Configuration v3.0.0-dev-00119
  • Serilog.Sinks.MSSqlServer v5.1.2

Answer

agua from mars picture agua from mars · Aug 31, 2018

I configure it like that:

return WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration
                .ReadFrom.Configuration(hostingContext.Configuration))
            .Build();

by default Serilog look for Serilog section in configuration