I'm trying to control LogLevel in log from appsetting.json. I've added my Nlog config here and custom field LogLevel. In rules I've added "${configsetting:item=LogLevel}"
and it works. But I want to be able to change LogLevel when app is running. So I add autoReload
to json and reloadOnChange = true
to ConfigurationBuilder. But it's not working for NLog.
Some of appsetting.json
:
"LogLevel": "Info",
"NLog": {
"throwConfigExceptions": true,
"autoReload": true,
"internalLogToConsole": true,
"extensions": [
{ "assembly": "SumoLogic.Logging.NLog" }
],
"targets": {
"async": true,
"fileTarget": {
"type": "File",
"fileName": "${gdc:item=mainLogFileName}",
"layout":"${longdate}|${level:uppercase=true}|${logger}|${message:exceptionSeparator=\r\n:withException=true}"
},
"errorFileTarget": {
"type": "File",
"fileName": "${gdc:item=errorLogFileName}",
"layout":"${longdate}|${level:uppercase=true}|${logger}|${message:exceptionSeparator=\r\n:withException=true}"
},
"consoleTarget": {
"type": "Console",
"layout":"${message:exceptionSeparator=\r\n:withException=true}"
}
},
"rules": [
{
"logger": "*",
"minLevel": "${configsetting:item=LogLevel}",
"writeTo": "consoleTarget"
},
{
"logger": "*",
"minLevel": "${configsetting:item=LogLevel}",
"writeTo": "fileTarget"
},
{
"logger": "*",
"minLevel": "Error",
"writeTo": "errorFileTarget"
},
]
}
And my code is
var config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", false, true)
.AddCommandLine(args)
.AddEnvironmentVariables()
.AddUserSecrets(Assembly.GetExecutingAssembly())
.Build();
ConfigSettingLayoutRenderer.DefaultConfiguration = config;
LogManager.Configuration = new NLogLoggingConfiguration(config.GetSection("NLog"));
LogManager.ReconfigExistingLoggers();
The only way it works for me:
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
ConfigSettingLayoutRenderer.DefaultConfiguration = _config;
LogManager.Configuration = new NLogLoggingConfiguration(_config.GetSection("NLog"));
LogManager.ReconfigExistingLoggers();
but it means to write it under every log.
Is there any nice way to reload NLog with appsetting?
Make sure to update the appsettings.json file that has been "deployed" with your application. Ex. in Debug- or Release- output-folder.
Microsoft Extension Logging will not react to updating appsettings.json in the Visual Studio Solution-folder.