Console Logging in .NET Core 6?

Viewed 3157

Using .NET 6 Core for a console app and I can't get debug logging working (nothing is displayed). And, I have added Microsoft.Extensions.Logging.Console to the project.

You'll see two ways below that I've attempted to get a reference to the logger.

Notice that logger.LogInformation does work, but logger.LogDebug does not.

Question: How do I get LogDebug working?

Program.cs

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

var serviceProvider = new ServiceCollection()
                            .AddLogging(builder => {
                                builder.ClearProviders();
                                builder.AddConsole();
                                builder.AddDebug();
                            })
                            .BuildServiceProvider();

// I've tried this
var logger = serviceProvider.GetService<ILogger<Program>>();

// And this
var logger = serviceProvider.GetService<ILoggerFactory>().CreateLogger<Program>>();

logger.LogDebug("hello world");       // <-- This DOESN'T work
logger.LogInformation("something");   // <-- This DOES work
3 Answers

Just to have here complete working example for .NET Core 6. You should add packages Microsoft.Extensions.Logging.Console to the project. (In my case its version is 6.0.0)

Program.cs

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

ServiceProvider serviceProvider = new ServiceCollection()
    .AddLogging((loggingBuilder) => loggingBuilder
        .SetMinimumLevel(LogLevel.Trace)
        .AddConsole()
        )
    .BuildServiceProvider();

var logger = serviceProvider.GetService<ILoggerFactory>().CreateLogger<Program>();

//Now both are working
logger.LogDebug("Debug World");         
logger.LogInformation("Hello World");

There is documentation on how to Create logs in Main:

IHost host = Host.CreateDefaultBuilder(args).Build();
var logger = host.Services.GetRequiredService<ILogger<Program>>();
logger.LogDebug("Host created.");
// ...

Once you have an IHost created via CreateDefaultBuilder, this allows you to take advantage of the appsettings.json file (see Configure logging):

{
  "Logging": {
    "LogLevel": {
      "Default": "Debug", // set default logs to debug level
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }
}

Just don't forget to copy appsettings.json to the output in your .csproj file. This is not done by default for Console applications and was what I was missing.

<ItemGroup>
  <None Update="appsettings.json">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  </None>
</ItemGroup>

You need to add the following to log Debug:

builder.SetMinimumLevel(LogLevel.Debug);
Related