I'm building a .Net Core 3.1 console app and I want to use the build in console logging. There are a zillion articles on .net logging, but I have not been able to find a sample that actually does write in the console.
namespace test
{
class Program
{
static void Main(string[] args)
{
var serviceProvider = new ServiceCollection()
.AddLogging(config => config.ClearProviders().AddConsole().SetMinimumLevel(LogLevel.Trace))
.BuildServiceProvider();
//configure console logging
serviceProvider
.GetService<ILoggerFactory>();
var logger = serviceProvider.GetService<ILoggerFactory>()
.CreateLogger<Program>();
logger.LogDebug("All done!");
Console.Write("Yup");
}
}
It compiles and runs, and even writes "Yup" to the console, but the "All done!" is not shown. Output in console window:
This is my sample project structure:
What am I missing?
It was a dispose of Services: Fix thanks to Jeremy Lakeman:
static void Main(string[] args)
{
using (var serviceProvider = new ServiceCollection()
.AddLogging(config => config.ClearProviders().AddConsole().SetMinimumLevel(LogLevel.Trace))
.BuildServiceProvider())
{
//configure console logging
serviceProvider
.GetService<ILoggerFactory>();
var logger = serviceProvider.GetService<ILoggerFactory>()
.CreateLogger<Program>();
// run app logic
logger.LogDebug("All done!");
}
Console.Write("Yup");
}
So that logging doesn't adversely impact the performance of your program, it may be written asynchronously.
Disposing the log provider and other logging classes should cause the log to flush.
The service provider should also dispose all services when it is disposed.