Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix obsolete ILoggerFactory methods?

I upgraded my project to .NET Core 2.2.x and got an obsolete warning regarding the following code - both lines:

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

The suggestion to fix is The recommended alternative is AddConsole(this ILoggingBuilder builder). I thought that is what I am using.

What am I missing here?

like image 890
AngryHacker Avatar asked Dec 18 '18 20:12

AngryHacker


3 Answers

I had the same issue today.

Remove your logging configuration from Startup.cs and go to your Program.cs file and add something like:

var host = new WebHostBuilder()
    .UseKestrel()
    .UseContentRoot(Directory.GetCurrentDirectory())
    .UseIISIntegration()
    .UseStartup<Startup>()
    .ConfigureLogging((hostingContext, logging) =>
    {
        logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
        logging.AddConsole();
        logging.AddDebug();
    })
    .Build();

This used the 'builder' because the variable 'logging' is an IloggingBuilder (whereas your code is still using ILoggerFactory)

UPDATE: The other method I just tried is to stay inside Startup.cs but move the logging stuff from the 'Configure' method to 'ConfigureServices' like this:

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

Perhaps keeps the Program.cs less polluted...

like image 127
Michael Ceber Avatar answered Oct 19 '22 00:10

Michael Ceber


The documentation's recommendation to use AddConsole(this ILoggingBuilder builder) is correct, but for that to work you need to add a reference to the NuGet package Microsoft.Extensions.Logging.Console.

like image 21
x5657 Avatar answered Oct 18 '22 23:10

x5657


I got the same warning when I was updating logging code from .Net Core 2.1 to 3.0. The recommended way to do the upgrade is documented on MSDN.

In my case, I was trying to get an instance of LoggerFactory for console which is pretty straightforward in .Net Core 3.0:

using (var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole()))
{
    // use loggerFactory
}
like image 16
meJustAndrew Avatar answered Oct 18 '22 22:10

meJustAndrew