Search code examples
c#asp.net-coreserilog

Custom Serilog config possible from Program.cs?


I'm generating a custom config in ASP.NET Core during the Startup constructor, something like this:

public Startup(IWebHostEnvironment environment, IConfiguration configuration) {
    Environment = environment;

    // Add extra config - configs added later override ones added earlier when key names clash
    Configuration = new ConfigurationBuilder()
        .AddConfiguration(configuration)
        .AddXmlFile("appsettings.xml")
        .Build();
}

My problem is that, while this new IConfiguration can be accessed from ConfigureServices and Configure, it can't be accessed from the .UseSerilog() call in CreateHostBuilder (Program.cs). So, I can't access my XML config at the time of my call:

webBuilder
    .UseStartup<Startup>()
    .UseSerilog((context, config) => {
        config.ReadFrom.Configuration(context.Configuration);
    });

How can I get around this? Can I make the new configuration available to the UseSerilog() lambda, or can I configure the logger later, in ConfigureServices()?


Solution

  • OK, I found out I can just .UseConfiguration() earlier in the IWebHostBuilder chain (instead of in the Startup constructor) to pull in my XML config settings:

    webBuilder
        .UseConfiguration(new ConfigurationBuilder().AddXmlFile("appsettings.xml").Build())
        .UseSerilog((context, config) => {
            config.ReadFrom.Configuration(context.Configuration);
        })