Dynamically Set NLog Levels in Code

NLog variable to set the log level on startup in .NET / .NET Core

NLog Configuration with Variables

<!-- rules to map from logger name to target -->
<rules>
<logger name="Microsoft.*" maxLevel="${var:logLevel}" final="true" />
<logger name="*" minlevel="${var:logLevel}" writeTo="Console" />
<logger name="*" minlevel="${var:logLevel}" writeTo="Logstash" />
</rules>

Setting Your NLog Level at Startup

<PackageReference Include="NLog" Version="4.7.13" />
<PackageReference Include="NLog.StructuredLogging.Json" Version="4.0.0" />
<PackageReference Include="NLog.Web.AspNetCore" Version="4.14.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="1.7.4" />
"env" : {
"LOGLEVEL" : "3"
},
var logger = 
NLog.Web.NLogBuilder.ConfigureNLog("nlog.config")
.GetCurrentClassLogger();
if (string.IsNullOrEmpty(
Environment.GetEnvironmentVariable("LOGLEVEL")))
NLog.LogManager.Configuration.Variables["logLevel"]
= "Warn";
else {
switch (Environment.GetEnvironmentVariable("LOGLEVEL"))
{
case "5":
NLog.LogManager.Configuration.Variables["logLevel"] = "Critical";
break;
case "4":
NLog.LogManager.Configuration.Variables["logLevel"] = "Error";
break;
case "3":
NLog.LogManager.Configuration.Variables["logLevel"] = "Warn";
break;
case "2":
NLog.LogManager.Configuration.Variables["logLevel"] = "Info";
break;
case "1":
NLog.LogManager.Configuration.Variables["logLevel"] = "Debug";
break;
case "0":
NLog.LogManager.Configuration.Variables["logLevel"] = "Trace";
break;
default:
NLog.LogManager.Configuration.Variables["logLevel"] = "Warn";
break;
}
}
// reset based on the variable passed in
NLog.LogManager.ReconfigExistingLoggers();

Test Your NLog Configuration

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store