Search code examples
c#loggingasp.net-core.net-core.net-core-logging

ILoggerFactory vs serviceCollection.AddLogging vs WebHostBuilder.ConfigureLogging


I have typical logging requirement for my asp.net core 2.x app:

  • use application insight in production,
  • console and debug logger in development env
  • setup some filters based on category and log level

Now I see at least three different API's to configure the logging:

  1. WebHostBuilder.ConfigureLogging()in Program.cs

    public static void Main(string[] args)
    {
        var webHost = new WebHostBuilder()               
            .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                logging.AddConsole();
                logging.AddDebug();
                logging.AddAzureWebAppDiagnostics();
            })
            .UseStartup<Startup>()
            .Build();
    
        webHost.Run();
    }
    
  2. Inject ILoggerFactory to Startup.Configure method:

    public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory, IServiceProvider serviceProvider)
    {
        loggerFactory.AddConsole();
        loggerFactory.AddAzureWebAppDiagnostics();
        loggerFactory.AddApplicationInsights(app.ApplicationServices, 
            (category, level) => level >= (category == "Microsoft" ? LogLevel.Error : LogLevel.Information));
        }
    
  3. in Startup.ConfigureServices:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddLogging(logging => 
        {
            logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
            logging.AddConsole();
            logging.AddDebug();
            logging.AddAzureWebAppDiagnostics();
        }
    }
    

What is the difference between those? When to use which?


Solution

  • The third one uses ConfigureServices which is a public method in the WebHostBuilder. The first one uses ConfigureLogging which is one of IHostBuilder's extension methods in HostingHostBuilderExtensions.

    They both call the IServiceCollection's extension method AddLogging in LoggingServiceCollectionExtensions under the Microsoft.Extensions.Logging package. The AddLogging method first tries to add two singletons ILoggerFactory and ILogger<> and an enumerable of LoggerFilterOptions, then it does the action for logging(ILoggingBuilder) which finally calls the AddProvider method to add the log providers implemented by these providers(Console, Azure) and calls SetMinimumLevel to add LoggerFilterOptions.

    The second method directly adds the log providers to LoggerFactory. And these providers are called in LoggerFactory when logging methods are called.

    As for orders, the second and third methods are called by WebHostBuilder's UseStartup<TStartup> method.