Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to set the minlevel of a NLog logger via a variable?

Tags:

nlog

Using NLog v4.4.12, I have this in my App.config

<nlog>
    <include file="..\Common\Logs\Variables.xml" />
    <rules>
        <logger name="*" minlevel="${logLevel}" writeTo="LogFile, Wcf"/>
    </rules>
</nlog>

And here is my Variables.xml file content

<?xml version="1.0" encoding="utf-8"?>
<nlog autoReload="true">
  <variable name="logLevel" value="Fatal" />
</nlog>

But I get an Exception when launching my app

Unknown log level: ${logLevel}

Am I doing something wrong or is it just impossible?

The goal of this is to eventually have an xml file per project that need to log things so each project can have his own minlevel and be able to change it at runtime via the edition of this xml.

Edit: Adding this code just before the Exception is thrown shows that my variable is there with the desired value.

var nl = NLog.LogManager.Configuration;
if (nl != null)
{
    if (nl.Variables.ContainsKey("logLevel"))
    {
            Console.WriteLine(nl.Variables["logLevel"]);
    }
}
like image 541
cakeby Avatar asked Sep 03 '25 04:09

cakeby


1 Answers

** Updated Answer **

NLog ver. 4.6 added support for using NLog-Config-Variables in minLevel. See https://github.com/NLog/NLog/pull/2709

NLog ver. 4.6.7 added support for adjusting minLevel at runtime, by modifying NLog-Config-Variables and calling ReconfigExistingLoggers(). See https://github.com/NLog/NLog/pull/3184

** Original Answer **

Unfortunately you can't use layout renderers (the ${...}) in the <logger> attributes like minLevel, level, etc

There are two options:

Use filters

 <logger name="*"  writeTo="LogFile, Wcf">
      <filters>
          <when condition="(level &lt; ${logLevel})" action="Ignore"/>
      </filters>      
 </logger>

Downsides:

  • less readable
  • hurt performance more compared to the minLevel attribute

Change the rules in code

var rule = config.LoggingRules[0];
// disable old levels, enable new
rule.DisableLoggingForLevel(LogLevel.Debug);
rule.DisableLoggingForLevel(LogLevel.Trace);
rule.EnableLoggingForLevels(LogLevel.Info, LogLevel.Fatal);

//apply config
LogManager.Configuration = config;
like image 111
Julian Avatar answered Sep 07 '25 18:09

Julian