-
Notifications
You must be signed in to change notification settings - Fork 1.4k
ConfigSetting Layout Renderer
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
${configsetting:item=String:default=String}
-
item - Key in the config. Required. Use
.for nested objects. - Default - Default value if not present. Optional.
${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;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
- Troubleshooting Guide - See available NLog Targets and Layouts: https://nlog-project.org/config
- Getting started
- How to use structured logging
- Troubleshooting
- FAQ
- Articles about NLog
-
All targets, layouts and layout renderers
Popular: - Using NLog with NLog.config
- Using NLog with appsettings.json