Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging in console application (.NET Core with DI)

guys. I try to add logging to my console app with DI (.NET Core 3.1) and seems that IoC container works fine for that, injects logger dependency to my classes, but LogXXX method doesn't log to output. What can be the reason? Maybe there are some additional configurations?

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace DependencyInjection
{
    class Program
    {
        static void Main(string[] args)
        {
            var services = new ServiceCollection();
            ConfigureServices(services);

            var serviceProvider = services.BuildServiceProvider();

            var logger = serviceProvider.GetService<ILogger<Program>>();
            logger.LogInformation("Hello world!");
        }

        static void ConfigureServices(ServiceCollection services)
        {
            services.AddLogging(loggerBuilder =>
            {
                loggerBuilder.ClearProviders();
                loggerBuilder.AddConsole();
            });
        }
    }
}
like image 364
Ivan Khorin Avatar asked Mar 14 '20 23:03

Ivan Khorin


People also ask

How do I log into .NET Core?

Set the environment key Logging:LogLevel:Microsoft to a value of Information on Windows. Test the settings when using an app created with the ASP.NET Core web application templates. The dotnet run command must be run in the project directory after using set .

What is the use of ILogger in .NET Core?

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.

Which logging framework is best for .NET Core?

NLog is one of the most popular, and one of the best-performing logging frameworks for . NET. Setting up NLog is fairly simple. Developers can use Nuget to download the dependency, then edit the NLog.


1 Answers

Docs have current example for Console App

class Program
{
    static void Main(string[] args)
    {
        using var loggerFactory = LoggerFactory.Create(builder =>
        {
            builder
                .AddFilter("Microsoft", LogLevel.Warning)
                .AddFilter("System", LogLevel.Warning)
                .AddFilter("LoggingConsoleApp.Program", LogLevel.Debug)
                .AddConsole();
        });
        ILogger logger = loggerFactory.CreateLogger<Program>();
        logger.LogInformation("Example log message");
    }
}

Of course you need to install the appropriate Nuget packages:

  • Microsoft.Extensions.Logging
  • Microsoft.Extensions.Logging.Console
like image 160
Mark Nadig Avatar answered Oct 21 '22 04:10

Mark Nadig