Skip to content

ConfigSetting Layout Renderer

Rolf Kristensen edited this page Oct 26, 2025 · 20 revisions

Lookup value from the appsettings.json or appsettings.Production.json and other configuration sources/overrides.

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

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.

Setup ConfigSetting

${configsetting} depends on Microsoft.Extensions.Configuration being loaded and available, so if using UseNLog() or AddNLog() on HostBuilder then everything will work out-of-the-box.

But if needing to load NLog configuration early before HostBuilder is ready, then ${configsetting} will not resolve the expected values, which might cause NLog Targets not using the expected configuration values. It is possible to setup ${configsetting} manually for these situations.

NLog Fluent Setup using LoadConfigurationFromAppSettings() from NLog.Web.AspNetCore nuget-package:

var logger = LogManager.Setup()
                       .LoadConfigurationFromAppSettings()
                       .GetCurrentClassLogger();

NLog Fluent Setup using LoadConfigurationFromSection(() from NLog.Extensions.Logging nuget-package:

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

NLog v4 can perform manual registration like this with NLog.Extensions.Logging nuget-package:

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

Examples

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