ILoggerFactory 对比 serviceCollection.AddLogging 对比 WebHostBuilder.ConfigureLogging

ILoggerFactory vs serviceCollection.AddLogging vs WebHostBuilder.ConfigureLogging

我的 asp.net 核心 2.x 应用程序有典型的日志记录要求:

现在我看到至少三种不同的 API 配置日志记录:

  1. WebHostBuilder.ConfigureLogging()在Program.cs

    public static void Main(string[] args)
    {
        var webHost = new WebHostBuilder()               
            .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                logging.AddConsole();
                logging.AddDebug();
                logging.AddAzureWebAppDiagnostics();
            })
            .UseStartup<Startup>()
            .Build();
    
        webHost.Run();
    }
    
  2. 注入ILoggerFactory到Startup.Configure方法:

    public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory, IServiceProvider serviceProvider)
    {
        loggerFactory.AddConsole();
        loggerFactory.AddAzureWebAppDiagnostics();
        loggerFactory.AddApplicationInsights(app.ApplicationServices, 
            (category, level) => level >= (category == "Microsoft" ? LogLevel.Error : LogLevel.Information));
        }
    
  3. 在Startup.Configure服务中:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddLogging(logging => 
        {
            logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
            logging.AddConsole();
            logging.AddDebug();
            logging.AddAzureWebAppDiagnostics();
        }
    }
    

它们之间有什么区别?什么时候使用哪个?

第三个使用ConfigureServices,这是WebHostBuilder. And the first one use ConfigureLogging which is one of IHostBuilder's extension method in HostingHostBuilderExtensions中的public方法。

并且都在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中调用了IServiceCollection的扩展方法AddLogging来添加LoggerFilterOptions

第二种方法直接将日志提供者添加到LoggerFactory。当调用日志记录方法时,这些提供程序在 LoggerFactory 中被调用。

关于订单,第二种和第三种方法由WebHostBuilderUseStartup<TStartup>方法调用。

在 ASP.NET Core 3.x 中,第一个示例现在是认可的选项。正如 the documentation

所解释的
public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureLogging(logging =>
        {
            logging.ClearProviders();
            logging.AddConsole();
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

另一个变化是不再支持Startup.ConfigureServices方法中DI容器设置完成前写入日志:

  • 不支持将记录器注入启动构造函数。
  • 不支持将记录器注入 Startup.ConfigureServices 方法签名

也不支持在主机构造期间记录日志(因为尚未设置 DI 容器),文档建议创建一个 separate logger for that case.