ConsoleLoggerExtensions.AddConsole(ILoggerFactory)已过时代码修复

0
10

0x00.问题

netcoreapp2.2环境下,Startup.cs 代码配置如下

1  public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
2   {
3       loggerFactory.AddConsole();
4       
5        //……
6   }

运行输出警告:“ConsoleLoggerExtensions.AddConsole(ILoggerFactory)”已过时:“This method is obsolete and will be removed in a future version. The recommended alternative is AddConsole(this ILoggingBuilder builder).”

官方文档也注明此API已经过时。https://docs.microsoft.com/zh-cn/dotnet/api/microsoft.extensions.logging.consoleloggerextensions.addconsole?view=aspnetcore-2.2#Microsoft_Extensions_Logging_ConsoleLoggerExtensions_AddConsole_Microsoft_Extensions_Logging_ILoggingBuilder_

0x01.推荐方法

Program.cs 配置如下

 1 public class Program
 2 {
 3     public static void Main(string[] args)
 4     {
 5         CreateWebHostBuilder(args).Build().Run();
 6     }
 7 
 8     public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
 9         WebHost.CreateDefaultBuilder(args)
10             .UseStartup<Startup>() 
11             .ConfigureLogging((hostingContext, logging) =>
12             {
13                 logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
14                 logging.AddConsole();
15                 logging.AddDebug();
16             });
17 }

或者Startup.cs ConfigureServices方法中配置如下

 1 public void ConfigureServices(IServiceCollection services)
 2 {
 3     services.AddLogging(logging =>
 4     {
 5         logging.AddConsole();
 6         logging.AddDebug();
 7     }); 
 8 
 9     //……
10 }

<

发布回复

请输入评论!
请输入你的名字