ILoggerFactory vs serviceCollection.AddLogging vs WebHostBuilder.ConfigureLogging
The third one use ConfigureServices
which is a public method in the WebHostBuilder
. And the first one use ConfigureLogging
which is one of IHostBuilder
's extension method in HostingHostBuilderExtensions
.
And they both call the IServiceCollection
's extension method AddLogging
in LoggingServiceCollectionExtensions
under Microsoft.Extensions.Logging
package. The AddLogging
method first try to add two singleton ILoggerFactory
and ILogger<>
and an enumerable of LoggerFilterOptions
. Then do the action for logging(ILoggingBuilder
) which finally calls 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.
In ASP.NET Core 3.x, the first example is now the endorsed option. As explained by the documentation
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.AddConsole();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
Another change is that writing logs before completion of the DI container setup in the Startup.ConfigureServices method is no longer supported:
- Logger injection into the Startup constructor is not supported.
- Logger injection into the Startup.ConfigureServices method signature is not supported
Logging during the host construction is also not supported (since the DI container is not yet set up), the documentation advises to create a separate logger for that case.