Logging in .Net core console application not working

Turns out the console logging provider doesn't immediately flush the messages to the console like it did in the net-core-1.x versions. It appears to run on a different thread. See this web page for info: https://github.com/aspnet/Logging/issues/631

You can add at the end of the Main function.

serviceProvider.Dispose();

or you can add .AddDebug()

            serviceProvider
            .GetService<ILoggerFactory>()
            .AddConsole(LogLevel.Debug)
            .AddDebug();

Creating a new ServiceProvider and HostBuilder may not be worth it if we just want a Logging in Console Application because it's a bit of extra caution to clean it up or dispose of. Rather, I would suggest just have Logging Factory to use logger and that will solve the logging if that is only what we want.

public static class ApplicationLogging
{
    public static ILoggerFactory LogFactory { get; } = LoggerFactory.Create(builder =>
        builder.ClearProviders(); 
        // Clear Microsoft's default providers (like eventlogs and others)
        builder.AddSimpleConsole(options =>
        {
            options.IncludeScopes = true;
            options.SingleLine = true;
            options.TimestampFormat = "hh:mm:ss ";
        });
        builder.AddApplicationInsights("instrument-key");
    });
    public static ILogger<T> CreateLogger<T>() => LogFactory.CreateLogger<T>();
}

static void Main(string[] args)
{
    var logger = ApplicationLogging.CreateLogger<Program>();
    logger.LogInformation("Let's do some work");
    logger.LogWarning("I am going Crazy now!!!");
    logger.LogInformation("Seems like we are finished our work!");
    Console.ReadLine();
}

Tags:

C#

.Net

.Net Core