Can I directly Inject ILogger without LoggerFactory

367 Views Asked by At

From the IoC perspective, we should be able to easily setup and choose the implementation of a interface.

If I create custom implementation of ILogger, can I directly injected it to controller without the ILoggerFactory-ILoggerProvider-ILogger structure?

In this way I can have less setting overhead and more control on the Logger. For example, I can cast and access the CustomProperty. In contrast, the logger created by ILoggerFactory-ILoggerProvider-ILogger chain will maintain a collection of ILoggers and I can not access my CustomLogger any more.

The code will look like below. Is this a feasible solution?

Define CustomLogger

public class CustomLogger : ILogger
{
   public CustomPropertyType CustomProperty;

   public CustomLogger(){...}
   public IDisposable BeginScope<TState>(TState state){...}
   public bool IsEnabled(LogLevel logLevel){...}

   public void Log<TState>(
            LogLevel logLevel,
            EventId eventId,
            TState state,
            Exception exception,
            Func<TState, Exception, string> formatter)
   {
      // Use some info from CustomProperty in while sending the log
   }
}

Setup the Dependency Injection

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<ILogger, CustomLogger>();
    //Other logic
}

Access the ILogger with CustomLogger implementation

public ExampleController(ILogger logger)
{
    this.logger = logger;
    this.customProperty = (CustomLogger)logger.CustomProperty;
}
1

There are 1 best solutions below

2
On

Yes, you need a provider. You can add this in the Startup class of your .NET Core application. Such code shall look like this:

loggerFactory.AddProvider(new CustomLoggerProvider(new CustomLoggerConfiguration()));

Here is an explanation of such usage. And here is an example.