How to create a LoggerFactory with a ConsoleLoggerProvider?
Just in case, if someone wants to do it in ASP.NET Core composition root for efcore:
services.AddDbContext<DbContext>(opt => {
opt.AddSqlServer(Configuration.GetConnectionString("DefaultConnection"));
opt.UseLoggerFactory(LoggerFactory.Create(builder => { builder.AddConsole(); }));
});
In .NET Core 2.2, you can build an ILoggerFactory
without using obsolete methods through Microsoft's dependency injection framework. It's a little less verbose than the version where everything is constructed by hand. Here’s how:
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
IServiceCollection serviceCollection = new ServiceCollection();
serviceCollection.AddLogging(builder => builder
.AddConsole()
.AddFilter(level => level >= LogLevel.Information)
);
var loggerFactory = serviceCollection.BuildServiceProvider().GetService<ILoggerFactory>();
And in .NET Core 3.0, you can use LoggerFactory.Create:
var loggerFactory = LoggerFactory.Create(builder => {
builder.AddFilter("Microsoft", LogLevel.Warning)
.AddFilter("System", LogLevel.Warning)
.AddFilter("SampleApp.Program", LogLevel.Debug)
.AddConsole();
}
);
See also:
- Migrate from Microsoft.Extensions.Logging 2.1 to 2.2 or 3.0