LuftWaffle
LuftWaffle

Reputation: 306

Use IServiceProvider in Microsoft.Extensions.DependencyInjection.AddLogging extension method

I have an app in which i would like to configure NLog with a configuration file like this

services.AddLogging(loggingBuilder =>
    {
        loggingBuilder
            .ClearProviders()
            .AddNLog(projectInfo.GetNLogConfigPath())
            .AddFilter("Microsoft", LogLevel.Warning);
    })

However I would like to get this file location from a singleton service from DI. I searched for a service provider but all I found is the loggingBuilder service collection (for now projectInfo is a local variable).

Is there a way to get service provider in the AddLogging extension method action?

Upvotes: 1

Views: 716

Answers (1)

Rolf Kristensen
Rolf Kristensen

Reputation: 19867

You can use this AddNLog() extension method from NLog.Extensions.Logging

services.AddLogging(loggingBuilder =>
   {
      loggingBuilder.ClearProviders();
      loggingBuilder.AddNLog(serviceProvider => {
         var config = serviceProvider.GetService(typeof(IConfiguration)) as IConfiguration;
         var filename = config["MyValues:Value1"].ToString();
         return NLog.LogManager.Setup().LoadConfigurationFromFile(filename).LogFactory;
      });
   })

Then you have this appsettings.json:

{ 
   "MyValues": {
      "Value1": "NLog.config"
   }
}

Notice you could also just have the NLog-configuration in the appsettings.json.

Upvotes: 1

Related Questions