Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serilog ReadFrom Configuration

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
like image 958
j-hurst Avatar asked Aug 31 '18 13:08

j-hurst


2 Answers

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

like image 143
agua from mars Avatar answered Sep 20 '22 14:09

agua from mars


I configured like this

     public static void Main(string[] args)
     {
        var _config = new ConfigurationBuilder()
                    .AddJsonFile("loggerconfig.json")//mantained separate 
     config file.
                    .Build();
        Log.Logger = new LoggerConfiguration()
                    .ReadFrom.Configuration(_config)
                    .CreateLogger();
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseSerilog()
            .UseStartup<Startup>();

and this is the better way according to Serilog.

like image 25
Manjunatha DL Avatar answered Sep 17 '22 14:09

Manjunatha DL