Logging in console application (.NET Core with DI)

Viewed 13620

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();
            });
        }
    }
}
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
Related