发布于 4年前

ASP.NET Core 2.0 日志配置

ASP.NET Core 2.0的日志系统做了break change的升级。.NET Core 2.0日志配置的改变主要体现在三点:

  • 使用新的方法AddLogging和Builder API配置services
  • 允许在Program.cs使用WebHostBuilder配置日志
  • ASP.NET Core 2.0模板里的WebHost提供了默认配置

使用新的方法AddLogging和Builder API配置services

在1.x版本里配置日志需要在Startup.cs里使用Configure来配置,2.0则使用了services新的方法AddLogging和Builder API来配置services,如:

services.AddLogging(builder => builder
                .AddConsole()
                .AddDebug();

允许在Program.cs使用WebHostBuilder配置日志

1.x是在Startup.cs里配置日志,2.0则允许在Program.cs使用WebHostBuilder配置日志。这样做的好处是可以让Startup.cs聚焦于services的配置和中间件的pipeline。

var builder = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .ConfigureAppConfiguration((hostingContext, config) =>
                {
                    var env = hostingContext.HostingEnvironment;
                    config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                          .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
                    config.AddEnvironmentVariables();
                })
                .ConfigureLogging((hostingContext, logging) =>
                {
                    logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                    logging.AddConsole();
                    logging.AddDebug();
                });

ASP.NET Core 2.0模板里的WebHost提供了默认配置

WebHost会类似上面的例子配置日志。如果指向使用Console和Debug的日志,就不需要添加额外的代码,如:

WebHost.CreateDefaultBuilder(args)
    .UseStartup<Startup>()
    .ConfigureLoggin(logging => logging.AddEventLog())
    .Build();

如果想添加别的ILoggerProviders,可以使用ConfigureLogging来配置。如上面的示例。

©2020 edoou.com   京ICP备16001874号-3