Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Logging not outputing anything

I am trying to use logging for a c# console project. Every resource online seems to be for asp.net and using appsettings.json which is something that my project doesn’t seem to have so I expect it is something asp.net related. I found a video using the following example for logging.

using Microsoft.Extensions.Logging;

namespace ConsoleTesting;

internal class Program
{
    public static void Main()
    {

        var loggerFactory = LoggerFactory.Create(builder =>
                                          {
                                              builder.AddConsole();
                                          });

        var logger = loggerFactory.CreateLogger("Logger");

        logger.LogCritical("Critical");
        logger.LogDebug("Debug");
        logger.LogInformation("Information");


        Console.WriteLine("Hello World!");
    }
}

But this doesn’t print anything in the console apart from Hello World.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I believe the problem is one of timing/buffering. If you just add a Thread.Sleep(5000); to the end, I suspect you’ll see all the output. (I do on my computer.)

Of course, you don’t want to add a Thread.Sleep call to your real code – you really want to flush all the loggers.

By experimentation, it looks like disposing of the LoggerFactory does the right thing. In your simple example, you can do that just by changing the declaration into a using statement:

using var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());

The LoggerFactory will be disposed at the end of the method, which at least seems to flush the logger. I don’t yet have documentation to back this up as the right way of doing things though.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading