ankush
ankush

Reputation: 999

Use logging in ConfigureAppConfiguration method in ASP.NET Core

I have certian code in ConfigureAppConfiguration method I want to add few logs here I tried writing below code but it fails how can I fix this? Or is there any other way to do logging in this method:

public static IWebHostBuilder AddKeyVault(this IWebHostBuilder builder)
{
    return builder.ConfigureAppConfiguration(
        (context, config) =>
        {
            var loggerFactory = builder.Build().Services.GetRequiredService<ILoggerFactory>(); // code fails here
            var logger = loggerFactory.CreateLogger(typeof(WebHostBuilderCustomExtension));
            //  if (context.HostingEnvironment.IsProduction())
            {
                var cert = new X509Certificate2(File.ReadAllBytes("keyvaultcertificate.pfx"));
            
                var builtConfig = config.Build();
                
                config.AddAzureKeyVault(builtConfig["vaultname"], "8c372a04-8578-4c38-a58d-a821d85212cb",cert);
                logger.LogInformation($"connected to key vault {builtConfig["azure.keyvault.uri"]}");
            }

        });
}

I get the error below when I run this code:

enter image description here

This is how this method is called:

return WebHost.CreateDefaultBuilder(args).AddKeyVault()
    .UseStartup<Startup>();

Upvotes: 5

Views: 2078

Answers (1)

Edward
Edward

Reputation: 30056

For IWebHostBuilder, you could not build it twice as the error indicates.

For ServiceCollection, you will not be able to access the services like ILoggerFactory before build the host.

For a workaround, you will need to initialize your own ILoggerFactory manually like.

public static class WebHostBuilderCustomExtension
{
    public static IWebHostBuilder AddKeyVault(this IWebHostBuilder builder)
    {
        return builder.ConfigureAppConfiguration(
                        (context, config) =>
                        {
                            var loggerFactory = new LoggerFactory(); 
                            loggerFactory.AddConsole();
                            var logger = loggerFactory.CreateLogger(typeof(WebHostBuilderCustomExtension));
                            logger.LogInformation($"connected to key vault ");
                        });
    }
}

Upvotes: 3

Related Questions