Injecting IConfiguration into Serilog Setup

I building a console app using .NET 6 with DI by using Host.CreateDefaultBuilder.
I’m am also using Serilog for logging and I am facing an inconvenience that I would like to solve while setting up Serilog


IConfiguration configuration = new ConfigurationBuilder()
                               // .AddUserSecrets<Program>()

using IHost host =
        .ConfigureAppConfiguration(builder => builder.AddJsonFile("appsettings.json").AddUserSecrets<Program>())
        .UseSerilog(new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger())
        .ConfigureServices(services =>

There is code redundancy related to setting up IConfigaration.

Is there a way to use the configuration variable inside ConfigureAppConfiguration() ? Or is it possible to somehow inject the configuration inside UseSerilog so that I don’t have to create the configuration variable in the first place?

>Solution :

You can use another overload of the method .UseSerilog() that provides you more input.


void ConfigureLogger(HostBuilderContext context, LoggerConfiguration loggerConfiguration)

ConfigureLogger() will be called when the Host is being built. At that point in time, Configuration is already created.

Leave a Reply