ILoggerFactory does not contain a definition for addconsole

149 Views Asked by At

I have upgrade a project from .NET Core 2.1 to .NET 7.

The original project had the following segment in startup.cs:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
        loggerFactory.AddConsole(LogLevel.Debug);
        loggerFactory.AddConsole(LogLevel.Information);
        loggerFactory.AddConsole(LogLevel.Warning);
        loggerFactory.AddConsole(LogLevel.Error);
}

In the upgraded project I get an error:

Iloggerfactory does not contain a definition for AddConsole.

Wonder what the equivalent would be in .NET 7 ?

3

There are 3 best solutions below

0
On BEST ANSWER

Looking at some documentation, I found the following help to fix it:

        services.AddLogging(loggingBuilder =>
        {
            loggingBuilder.AddDebug();
            loggingBuilder.AddConsole();
        });

in ConfigureServices

0
On

In the .net 7, the console log is installed by default by the logging extension.

You could use below codes inside the program.cs

var builder = WebApplication.CreateBuilder(args);
builder.Logging.SetMinimumLevel(LogLevel.Debug);
builder.Logging.AddConsole();

The SetMinimumLevel is used for set the log level for the LogDebug,LogInformation,LogWarning,LogError,Critical.

You could also set it by using the appsettings.json, like below

  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "Microsoft.AspNetCore": "Warning"
    }
  }

More details about how to use it inside the .net 7, I suggest you could refer to this article.

2
On

Make sure this package is installed in your project Microsoft.Extensions.Logging.Console.

I would have the Configure in Startup.cs like this:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    LoggerFactory.Create(builder =>
    {
        builder.SetMinimumLevel(LogLevel.Debug);
        builder.AddFilter("Microsoft", LogLevel.Information);
        builder.AddFilter("System", LogLevel.Warning);

        builder.AddConsole();
    });
}

You can find more here Logging.

Another Option is to do this in your Program.cs

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args).ConfigureLogging((logging) =>
    {
        logging.ClearProviders(); //Optional: Remove other logging providers if needed.

        logging.AddConsole(options =>
        {
            // Set the minimum log level for the console
            options.LogToStandardErrorThreshold = LogLevel.Debug;
        });
    })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });