How to instantiate a logger implementing Microsoft.Extensions.Logging.ILogger<T> that logs to Serilog logger

Viewed 3338

How do I instantiate a logger implementing Microsoft.Extensions.Logging.ILogger<out TCategoryName> that will output logs to my Serilog logger, when I cannot do it via standard ASP.NET Core dependency injection?

I have Serilog configured in my ASP.NET Core project, and the standard dependency injection set up is correctly injecting loggers into my controllers and services. The output from these loggers is correctly written to the file as specified in my Serilog configuration.

However, I need to pass a logger to an object that is instantiated during Startup.ConfigureServices(...), so I cannot resolve it via DI. I can instantiate a Serilog.Logger, but since I want to avoid direct dependencies on Serilog outside of my configuration code, I am forced to use my own adaptor. I would expect there to be some existing adaptor that would use Microsoft.Extensions.Logging.ILogger<out TCategoryName>, but I can't work out how to do it.

The precise use case is to inject a logger into a DbCommandInterceptor, which I am trying to do inside Startup.ConfigureServices(...):

var databaseConfiguration = this.Configuration
    .GetSection(nameof(DatabaseConfiguration))
    .Get<DatabaseConfiguration>();
var interceptor = new LoggingDbCommandInterceptor(
    warning => Log.Logger.Warning("{Warning}", warning),
    error => Log.Logger.Error("{Error}", error),
    databaseConfiguration);
var dbConfiguration = new MyDbConfiguration(interceptor);
DbConfiguration.SetConfiguration(dbConfiguration);
1 Answers
Related