如何修复过时的 ILoggerFactory 方法?

我将我的项目升级到 .NET Core 2.2.x 并收到关于以下代码的过时警告 - 两行:

public void Configure(IApplicationBuilder app, 
                      IHostingEnvironment env, 
                      ILoggerFactory loggerFactory) 
  {
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));

修复的建议是The recommended alternative is AddConsole(this ILoggingBuilder builder)。我以为这就是我正在使用的。

我在这里想念什么?


函数式编程
浏览 217回答 4
4回答

POPMUISE

我今天有同样的问题。从 Startup.cs 中删除您的日志记录配置,然后转到您的 Program.cs 文件并添加如下内容:var host = new WebHostBuilder()&nbsp; &nbsp; .UseKestrel()&nbsp; &nbsp; .UseContentRoot(Directory.GetCurrentDirectory())&nbsp; &nbsp; .UseIISIntegration()&nbsp; &nbsp; .UseStartup<Startup>()&nbsp; &nbsp; .ConfigureLogging((hostingContext, logging) =>&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));&nbsp; &nbsp; &nbsp; &nbsp; logging.AddConsole();&nbsp; &nbsp; &nbsp; &nbsp; logging.AddDebug();&nbsp; &nbsp; })&nbsp; &nbsp; .Build();这使用了“builder”,因为变量“logging”是一个 IloggingBuilder(而您的代码仍在使用 ILoggerFactory)更新:我刚刚尝试的另一种方法是留在 Startup.cs 中,但将日志内容从“配置”方法移动到“配置服务”,如下所示:public void ConfigureServices(IServiceCollection services){&nbsp; &nbsp; services.AddLogging(loggingBuilder =>&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; loggingBuilder.AddConfiguration(Configuration.GetSection("Logging"));&nbsp; &nbsp; &nbsp; &nbsp; loggingBuilder.AddConsole();&nbsp; &nbsp; &nbsp; &nbsp; loggingBuilder.AddDebug();&nbsp; &nbsp; });}也许可以减少 Program.cs 的污染...

暮色呼如

文档的使用建议AddConsole(this ILoggingBuilder builder)是正确的,但要使其正常工作,您需要添加对 NuGet 包的引用Microsoft.Extensions.Logging.Console。

慕田峪4524236

当我将日志代码从 .Net Core 2.1 更新到 3.0 时,我收到了同样的警告。推荐的升级方法记录在 MSDN 上。就我而言,我试图为控制台获取 LoggerFactory 的实例,这在 .Net Core 3.0 中非常简单:using (var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole())){&nbsp; &nbsp; // use loggerFactory}

FFIVE

别担心 - 这是有史以来最愚蠢的事情!笔记以下代码示例使用在 2.2 版中已过时的 ConsoleLoggerProvider 构造函数。3.0 版将提供对过时日志 API 的适当替换。同时,忽略和抑制警告是安全的。如果您认为您忘记了Obsolete的含义 - 您没有!不要担心它,暂时忽略它 - 或抑制警告(对不起,我没有手头的代码)。(希望他们能更好地解释为什么要这样做——这就是我所说的愚蠢。)
打开App,查看更多内容
随时随地看视频慕课网APP