如何在 .net 6 中获取 ILoggerFactory

How to get ILoggerFactory in .net 6

在 .Net5 中,ILoggerFactory 在 Startup.cs 中用作配置函数,如下所示:

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

在 .Net6 中如何使用 aap 或 builder 获取它

var app = builder.Build();

var builder = WebApplication.CreateBuilder(args);

WebApplicationBuilder 公开可用的 Logging property which has AddProvider(ILoggingBuilder, ILoggerProvider) 扩展方法。尝试使用它:

builder.Logging.AddProvider(loggerprovider);

获取实际的记录器工厂实例:

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