Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging in .Net core console application not working

Tags:

c#

.net

.net-core

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");
like image 693
Mrug Avatar asked Jul 13 '18 13:07

Mrug


People also ask

How do you add a logger in .NET core console application?

For example, to add a console logger provider to the LoggerFactory , just call the LoggerFactory. AddConsole() extension method with the same parameters as ConsoleLoggerProvider , as shown below. public ILoggerFactory loggerFactory = new LoggerFactory(). AddConsole();

What is the use of ILogger in .NET core?

ILoggerFactory Interface ILoggerFactory is a factory interface that we can use to create instances of the ILogger type and register logging providers. It acts as a wrapper for all the logger providers registered to it and a logger it creates can write to all the logger providers at once.


1 Answers

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();
like image 117
Celal Yildirim Avatar answered Sep 22 '22 10:09

Celal Yildirim