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
.
CodePudding user response:
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.