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:
WebHostBuilder.ConfigureLogging()in Program.cspublic 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(); }Inject
ILoggerFactoryto 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)); }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?
The third one uses
ConfigureServiceswhich is a public method in theWebHostBuilder. The first one usesConfigureLoggingwhich is one ofIHostBuilder's extension methods inHostingHostBuilderExtensions.They both call the
IServiceCollection's extension methodAddLogginginLoggingServiceCollectionExtensionsunder theMicrosoft.Extensions.Loggingpackage. TheAddLoggingmethod first tries to add two singletonsILoggerFactoryandILogger<>and an enumerable ofLoggerFilterOptions, then it does the action for logging(ILoggingBuilder) which finally calls theAddProvidermethod to add the log providers implemented by these providers(Console, Azure) and callsSetMinimumLevelto addLoggerFilterOptions.The second method directly adds the log providers to
LoggerFactory. And these providers are called inLoggerFactorywhen logging methods are called.As for orders, the second and third methods are called by
WebHostBuilder'sUseStartup<TStartup>method.