Search code examples
asp.net-corenlogappsettings

Can i "outsource" the NLog-portion of appsettings.json?


I have a bunch of different appsettings.json for a number of customers. However, the nLog-portion of these appsettings never changes, so I'd love to have one single json-File for the nLog-config. So I have something like the following in my appsettings.json:

"NLog": {
    "configFile": "nlog.json"
}

Does anybody know a more or less easy solution for that?


Solution

  • You could try extracting section into separate file and add it with ConfigurationBuilder, like in below example.

    I have two settings files:

    • appsettings.dev.json - all app settings
    • appsettings.nlog.dev.json - with single NLog section

    Both files need to be copied to output directory.

    var config = new ConfigurationBuilder()
        .AddJsonFile("appsettings.dev.json", false)
        .AddJsonFile("appsettings.nlog.dev.json", false)
        .Build();
    
    using var servicesProvider = new ServiceCollection()
              .AddLogging(loggingBuilder =>
              {
                  // configure Logging with NLog
                  loggingBuilder.ClearProviders();
                  var nlogConfig = new NLogLoggingConfiguration(config.GetSection("NLog"));
                  loggingBuilder.AddNLog(nlogConfig);
              }).BuildServiceProvider();