nreco / logging

Generic file logger for .NET Core (FileLoggerProvider) with minimal dependencies
MIT License
296 stars 60 forks source link

ImplementationType null injecting with .AddLogging() method #29

Closed MindaugasBernatavicius closed 3 years ago

MindaugasBernatavicius commented 3 years ago

Not yet sure why, but ImplementationType null injecting with .AddLogging() method. Advice would be appreciated. Also is there a simpler way of configuring this logging library with DI?

Screenshot: image

Minimal working example (uncomment the line that works):

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using CsvHelper;
using CsvHelper.Configuration;
using Newtonsoft.Json;
using Microsoft.Extensions.DependencyInjection;
using NReco.Logging.File;
using Microsoft.Extensions.Logging;

class Program
{
    static void Main()
    {
        var services = new ServiceCollection();

        services
            //.AddSingleton<ILogger>(new FileLogger("app.log", new FileLoggerProvider("app.log")))
            .AddLogging(loggingBuilder => loggingBuilder.AddFile("app.log", append: true))
            .AddTransient<Appy>();

        var serviceProvider = services.BuildServiceProvider();

        var app = serviceProvider.GetService<Appy>();
        app.logSomething();
    }

}

class Appy
{
    private readonly ILogger _logger;

    public Appy(ILogger logger)
    {
        _logger = logger;
    }

    public void logSomething()
    {
        _logger.LogInformation($"MyApplication Started!");
    }
}
VitaliyMF commented 3 years ago

AddFile extension method is implemented here: https://github.com/nreco/logging/blob/master/src/NReco.Logging.File/FileLoggerExtensions.cs

It works just fine when used in MVC Core Startup.cs. I'm not sure what is wrong in your code -- have you tried to use standard logging provider, say, AddConsole, and check how it works?

MindaugasBernatavicius commented 3 years ago

Yea, sorry my mistake, the logger did not have the generic param: public Appy(ILogger logger) ... late night coding.