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");
}
I might be late but worth adding some inputs in case it helps. I was also struggling with this logging in .net core and keep having breaking changes with the latest release. However, can't complain as it keeps getting better and better. Here is what I have done with the .net core 5 released.
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 ";
}).SetMinimumLevel(LogLevel.Warning);
});
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();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With