17

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();
            });
        }
    }
}
Ivan Khorin
  • 827
  • 1
  • 5
  • 17
  • 5
    https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-3.1#add-providers and read the part about non hosted console app. you have to create the factory yourself – Nkosi Mar 14 '20 at 23:17
  • 2
    Actually, I've found that disposing serviceProvicer at the end of Main() solves the problem. Just added serviceProvider.Dispose(); – Ivan Khorin Mar 15 '20 at 07:43

1 Answers1

33

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
live2
  • 3,771
  • 2
  • 37
  • 46
Mark Nadig
  • 4,901
  • 4
  • 37
  • 46
  • 10
    How can I access the logger from another class? Is there a way to make it available by DI? – Lamar Oct 28 '22 at 22:38
  • Using serviceProvider from your original question, use var logger = serviceProvider.GetRequiredService>()) – balintn Jul 01 '23 at 20:33