Search code examples
asp.net-coreserilogini

How to configure Serilog using the `IniConfigurationProvider` in ASPNET Core


I am trying to adapt Serilog config examples that are provided in appSettings.json format to my ASPNET Core web application that must be configured with a .ini file (using Microsoft.Extensions.Configuration.Ini.IniConfigurationProvider`)

I want to see logs in the output console and add additional sinks using the config file.

My issue is that I don't understand how to translate nested JSON syntax into the flat format of the INI file.

Serilog is created in two-stage initialization. bootstrap in Program.cs as follows:

    Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                .Enrich.FromLogContext()
                .WriteTo.Console()
                .CreateBootstrapLogger();

Then in CreateHostBuilder function I replace it with actual configuration

    Host.CreateDefaultBuilder(args)
                     .ConfigureAppConfiguration((hostingContext, configuration) => {
                         configuration.Sources.Clear();
                         configuration.AddIniFile(@"config.ini", optional: false, reloadOnChange: false);
                     })
                    .UseSerilog((context, services, configuration) => configuration
                        .ReadFrom.Configuration(context.Configuration)
                        .ReadFrom.Services(services)
                        .Enrich.FromLogContext()
                        .WriteTo.Console())
                    .ConfigureWebHostDefaults(webBuilder =>
                    {
                        webBuilder.UseStartup<Startup>();
                    })

This is what I am trying now (without success)

    [Serilog]
    Level=Verbose
    
    [Serilog:Using]
    File = "Serilog.Sinks.File"
    
    [Serilog:Write-To]
    File.Path = "C:\myapp\log.txt"
    File.rollOnFileSizeLimit = true
    File.fileSizeLimitBytes = 10000000

Solution

  • Your syntax for the .ini file is not the correct one. Try this:

    [Serilog]
    Level=Verbose
    
    [Serilog:Using]
    File = "Serilog.Sinks.File"
    
    [Serilog:WriteTo:File]
    Name = "File"
    Args:Path = "C:\myapp\log.txt"
    Args:RollOnFileSizeLimit = true
    Args:FileSizeLimitBytes = 10000000
    

    I have tested it with a fresh ASP NET Core app and it works in my environment.