0

I have a .NET Core 3.1 application and I'm setting up the generic host as follows:

static void Main(string[] args)
{
    Host.CreateDefaultBuilder(args)
        .ConfigureLogging((context, loggingBuilder) =>
        {
            loggingBuilder.AddConsole();
            loggingBuilder.AddDebug();
        })
        .ConfigureAppConfiguration((context, configurationBuilder) =>
        {
            // I want to get an ILogger instance here, but how?
            configurationBuilder.Add(new CustomConfigurationSource(logger));
        })
        // some other setup logic
        .Build().Run();
}

The problem is that I want to use an ILogger when configuring app configurations. The configuration source I used needs to access a remote server, and also contains some complicated logic for configuration reload, so I want it to be able to write logs for diagnostic and monitoring purposes.

Is there any proper way that this can be done in .NET Core generic host? I would think that this is a pretty legit requirement but can't seem to figure out a way.

The same problem statement also applies to ASP.NET Core applications.

1 Answer 1

2

As far as I know, we couldn't access the Ilogger since the service hasn't been registered in CreateDefaultBuilder method.

If you want to use logger in the ConfigureAppConfiguration, I suggest you could try to create the logger by yourself.

Like below:

       Host.CreateDefaultBuilder(args)
 .ConfigureLogging((context, loggingBuilder) =>
 {
    
 })
 .ConfigureAppConfiguration((context, configurationBuilder) =>
 {
     using (var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole()))
     {
 
      var logger =   loggerFactory.CreateLogger(typeof(Program));
     logger.LogInformation("Example log message");
      }
     // I want to get an ILogger instance here, but how?


 })
 // some other setup logic
 .Build().Run();

Result:

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This seems to be the best workaround after I read through this GitHub issue. Feels like quite a limiting issue in generic host though

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.