'How to get ILoggerFactory in .net 6

In .Net5 ILoggerFactory is used as Configure function in Startup.cs as follows :

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
    //here we used loggerFactory
    loggerFactory.AddProvider(loggerprovider);
}

In .Net6 how to get it with aap or builder

var app = builder.Build();

OR

var builder = WebApplication.CreateBuilder(args);


Solution 1:[1]

WebApplicationBuilder exposes Logging property which has AddProvider(ILoggingBuilder, ILoggerProvider) extension method available. Try using it:

builder.Logging.AddProvider(loggerprovider);

Solution 2:[2]

To get the actual logger factory instance:

var app = builder.Build();
var lf = app.Services.GetRequiredService<ILoggerFactory>();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Guru Stron
Solution 2 John Goudy