Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 385
Gerald Hughes Avatar asked Sep 19 '17 08:09

Gerald Hughes


People also ask

What is Loggerfactory in .NET core?

It is designed as a logging API that developers can use to capture built-in ASP.NET logging as well as for their own custom logging. The logging API supports multiple output providers and is extensible to potentially be able to send your application logging anywhere.

What is the use of logger in C#?

Logging levels are used to filter logging output, tailoring the amount of data output to the situation in hand. Each logging level is associated with the type of data logged. DEBUG, INFO, and TRACE events are typically non-error conditions that report on the behavior of an application.


1 Answers

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;

like image 126
OlegI Avatar answered Sep 26 '22 09:09

OlegI