Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

Program.cs

IConfiguration configuration = new ConfigurationBuilder()
                              .AddJsonFile("appsettings.json")
                               // .AddUserSecrets<Program>()
                              .Build();

using IHost host =
    Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration(builder => builder.AddJsonFile("appsettings.json").AddUserSecrets<Program>())
        .UseSerilog(new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger())
        .ConfigureServices(services =>
         {...})
        .Build();

There is code redundancy related to setting up IConfigaration.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Host.CreateDefaultBuilder(args)
    .UseSerilog(ConfigureLogger);

void ConfigureLogger(HostBuilderContext context, LoggerConfiguration loggerConfiguration)
{
    loggerConfiguration.ReadFrom.Configuration(context.Configuration);
}

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading