Warm tip: This article is reproduced from serverfault.com, please click

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

发布于 2020-06-18 16:02:24

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");
        }
Questioner
k.c.
Viewed
0
Jeremy Lakeman 2020-06-20 18:04:03

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.