Skip to content

ConfigSetting Layout Renderer

Rolf Kristensen edited this page Jun 22, 2024 · 15 revisions

Value from the appsettings.json or other configuration in .NET Core

Introduced with NLog.Extensions.Logging 1.4.0 and NLog.Web.AspNetCore 4.8.0

Register Configuration

When calling UseNLog() from NLog.Web.AspNetCore or NLog.Extensions.Hosting then it will automatically register hosting environment configuration with ConfigSettingLayoutRenderer.

But to make ${configsetting} work during startup, before Host has been built, then NLog.Web.AspNetCore makes it easier to load appsettings.json (Since ver. 4.9.3):

// Loads appsetting.json and enables ${configsetting}
var logger = LogManager.Setup()
                       .LoadConfigurationFromAppSettings()
                       .GetCurrentClassLogger();

Manual loading of appsettings.json with fluent API (Available with NLog v5):

IConfigurationRoot config = new ConfigurationBuilder()
    .AddJsonFile(path: "AppSettings.json").Build();
var logger = LogManager.Setup()
                       .LoadConfigurationFromSection(config)
                       .GetCurrentClassLogger();

To manual register the Microsoft Extension IConfiguration with ${configsetting} for NLog v4:

IConfigurationRoot config = new ConfigurationBuilder()
    .AddJsonFile(path: "AppSettings.json").Build();
NLog.Extensions.Logging.ConfigSettingLayoutRenderer.DefaultConfiguration = config;

Configuration Syntax

${configsetting:item=String:default=String}

Parameters

Rendering Options

  • item - Key in the config. Required. Use . for nested objects.
  • Default - Default value if not present. Optional.

Example

Example: appsettings.json:

{
    "Mode":"Prod",
    "Options":{
        "StorageConnectionString":"UseDevelopmentStorage=true",
    }
}

Config Setting Lookup:

${configsetting:item=Mode} // renders "Prod"
${configsetting:item=Options.StorageConnectionString} // renders "UseDevelopmentStorage=true"
${configsetting:item=Options.TableName:default=MyTable} // renders "MyTable"

Config Setting Lookup Cached:

${configsetting:cached=True:item=Mode}

Notice appsettings.json gives the ability to make environment-specific overrides (Ex. appsettings.Production.json). See also Environment-specific-NLog-Logging-Configuration

Clone this wiki locally