7

I've using vs 2019 for a console application(dotnet core 3.1),

Install-Package Microsoft.Extensions.Logging.Console -Version 3.1.2 

and this code:

using Microsoft.Extensions.Logging;
class Program
{
    static void Main(string[] args)
    {
        var loggerFactory = LoggerFactory.Create(builder =>
        {
            builder
                .AddFilter("Microsoft", LogLevel.Information)
                .AddFilter("System", LogLevel.Information)
                .AddFilter("TestRx.Program", LogLevel.Information)
                .AddConsole();
        });
        ILogger logger = loggerFactory.CreateLogger<Program>();
        logger.LogInformation("Example log message");
    }
}

It doesn't print anything on console, why?

Troskyvs
  • 7,537
  • 7
  • 47
  • 115

1 Answers1

10

Depending on my hosting I could reproduce and it seems you need to dispose the LoggerFactory to flush the console output.

Probably this is a performance feature of newer .NET Core versions. Afaik the older ones directly printed it to console.

using var loggerFactory = LoggerFactory.Create(builder =>
{
    builder.AddConsole();
});
                
var logger = loggerFactory.CreateLogger<Program>();
logger.LogInformation("Example log message");

You can watch that kind of async nature of logging by creating tons of logs and either wait a bit or quit the program directly:

ILogger logger = loggerFactory.CreateLogger<Program>();
for (int i = 0; i < 1000; i++)
{
    logger.LogInformation("Example log message2");
}
//Thread.Sleep(1000);

The sleep will help to flush all logs!

live2
  • 3,771
  • 2
  • 37
  • 46
Falco Alexander
  • 3,092
  • 2
  • 20
  • 39