In Microsoft.Extensions.Logging 3.0+, you can use the much simpler LoggerFactory.Create:
var loggerFactory = LoggerFactory.Create(builder =>
{
builder.AddFilter("Microsoft", LogLevel.Warning)
.AddFilter("System", LogLevel.Warning)
.AddFilter("SampleApp.Program", LogLevel.Debug)
.AddConsole();
});
For Microsoft.Extensions.Logging version 2.2+, you can build an ILoggerFactory
without using obsolete methods via Microsoft’s dependency injection framework. It’s a little less verbose than the 2.1 version where everything is constructed by hand. Here’s how:
var serviceCollection = new ServiceCollection();
serviceCollection.AddLogging(builder => builder
.AddConsole()
.AddFilter(level => level >= LogLevel.Information)
);
var loggerFactory = serviceCollection.BuildServiceProvider()
.GetService<ILoggerFactory>();
See also:
- Migrate from Microsoft.Extensions.Logging 2.1 to 2.2 or 3.0