Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make console logger in .net core 3.1 console app work

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:console-output

This is my sample project structure: enter image description here

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");
        }
like image 993
k.c. Avatar asked Jun 18 '20 16:06

k.c.


Video Answer


2 Answers

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();
}
like image 66
Brijesh Shah Avatar answered Oct 08 '22 13:10

Brijesh Shah


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.

like image 32
Jeremy Lakeman Avatar answered Oct 08 '22 13:10

Jeremy Lakeman