How to Use LoggerFactory and Microsoft.Extensions.Logging for .NET Core Console Logging With C#

Gerald Hughes picture Gerald Hughes · Sep 19, 2017 · Viewed 24.2k times · Source

I've created a console application that uses a service layer.

Program.cs

public static void Main(string[] args)
{
    // Create service collection
    var serviceCollection = new ServiceCollection();
    ConfigureServices(serviceCollection);

    // Create service provider
    var serviceProvider = serviceCollection.BuildServiceProvider();

    // Entry to run app
    serviceProvider.GetService<App>().Run().RunSynchronously();
}

private static void ConfigureServices(IServiceCollection serviceCollection)
{
    // Configuration
    var configuration = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json", false)
        .Build();

    serviceCollection.AddOptions();
    serviceCollection.Configure<Settings>(options =>
    {
        //...
    });

    // Services
    serviceCollection.AddTransient<IOneService, OneService>();
    serviceCollection.AddTransient<ISecondService, SecondService>();

    // Repositories
    serviceCollection.AddTransient<MyContext, MyContext>();
    serviceCollection.AddTransient<IOneRepository, OneRepository>();

    // App
    serviceCollection.AddTransient<App>();

    // Logger

    // Automapper
    serviceCollection.AddSingleton(new AutoMapperProfileConfiguration());
    serviceCollection.AddScoped<IMapper>(sp =>
        new Mapper(sp.GetRequiredService<IConfigurationProvider>(), sp.GetService));
}

I'm getting this error System.InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger1` and I'm guessing that i have to setup LoggerFactory and Microsoft.Extensions.Logging for .NET Core Logging, but I can't get it right.

I've tried something like this in Main():

// Attempt 1
ILoggerFactory loggerFactory = new LoggerFactory()
    .AddConsole()
    .AddDebug();
ILogger logger = loggerFactory.CreateLogger<Program>();
logger.LogInformation(
  "This is a test of the emergency broadcast system.");

// Attempt 2
serviceCollection.AddSingleton(new LoggerFactory()
    .AddConsole()
    .AddDebug());

Any ideas?

Answer

OlegI picture OlegI · Sep 19, 2017

It should work:

var serviceProvider = new ServiceCollection()
                      .AddLogging() //<-- You were missing this
                      .BuildServiceProvider();
//get logger
var logger = serviceProvider.GetService<ILoggerFactory>()
            .CreateLogger<Program>();

Packages to install : Microsoft.Extensions.DependencyInjection; Microsoft.Extensions.Logging;