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

Logging in .Net core console application not working

发布于 2018-07-13 13:37:38

I am following this tutorial: https://andrewlock.net/using-dependency-injection-in-a-net-core-console-application/

and accordingly installed the packages but log is not getting printed anywhere.

This is my code:

  var serviceProvider = new ServiceCollection()
            .AddLogging()
            .AddTransient<IFoo, Foo>(s =>
            {
                return new Foo()})
            .BuildServiceProvider();

            //configure console logging
            serviceProvider
                .GetService<ILoggerFactory>()
                .AddConsole(LogLevel.Debug);

 var logger = serviceProvider.GetService<ILoggerFactory>().CreateLogger<Program>();

            logger.LogError("Starting application");
Questioner
Mrug
Viewed
0
Celal Yildirim 2018-07-14 00:44:47

Turns out the console logging provider doesn't immediately flush the messages to the console like it did in the net-core-1.x versions. It appears to run on a different thread. See this web page for info: https://github.com/aspnet/Logging/issues/631

You can add at the end of the Main function.

serviceProvider.Dispose();

or you can add .AddDebug()

            serviceProvider
            .GetService<ILoggerFactory>()
            .AddConsole(LogLevel.Debug)
            .AddDebug();