-
Notifications
You must be signed in to change notification settings - Fork 1.4k
ConfigSetting Layout Renderer
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
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;
${configsetting:item=String:default=String}
-
item - Key in the config. Required. Use
.
for nested objects. - Default - Default value if not present. Optional.
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