Asp.net core get logger in ConfigureAppConfiguration

2.3k views Asked by At

I would like to use logger in "TODO" line, because I need to log when I add a "AddJsonConfigurationSourceDecryption" method, Is there any way to get a logger?

Logging in ASP.NET Core

  public class Program
{

    public static void Main(string[] args)
    {
        ILogger<Program> logger = null;
        try
        {
            var host = CreateWebHostBuilder(args).Build();

            ApplicationLogging.LoggerFactory = host.Services.GetRequiredService<ILoggerFactory>();
            logger = host.Services.GetRequiredService<ILogger<Program>>();

            logger.LogInformation("start thin API service...");
            host.Run();
        }
        catch (Exception ex)
        {
            logger?.LogError(ex, "Stopped program because of exception");
            throw;
        }
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args)
    {
        return WebHost.CreateDefaultBuilder(args)
            .UseKestrel(option => option.AddServerHeader = false)
            .ConfigureLogging((host, builder) => { builder.SetMinimumLevel(LogLevel.Trace); })
            .UseNLog()
            .ConfigureServices(services => services.AddAutofac())
            .ConfigureAppConfiguration((context, builder) =>
            {
                //TODO: Logger.............
                builder.SetBasePath(Directory.GetCurrentDirectory());
                builder.AddJsonConfigurationSourceDecryption();
            })
            .UseStartup<Startup>();
    }
}
1

There are 1 answers

0
svonidze On

@0xced answered this question here How to create a LoggerFactory with a ConsoleLoggerProvider?

as of dotnetcore3.1 the code could be written this way

private static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args).ConfigureAppConfiguration(
                (hostContext, config) =>
                    {
                        var loggerFactory = LoggerFactory.Create(
                            builder => 
                                {
                                    builder
                                        .AddFilter("Microsoft", LogLevel.Warning)
                                        .AddFilter("System", LogLevel.Warning)
                                        .AddFilter("YourProgramNamespsace.Program", LogLevel.Debug)
                                        .AddConsole();
                                });
                        var logger = loggerFactory.CreateLogger<Program>();
                        logger.LogInformation("Hello from ConfigureAppConfiguration");
                    ...
                    })