Home > Back-end >  Nlog filter when condition with equals not working
Nlog filter when condition with equals not working

Time:03-13

I have to pass the variable value from my startup class

LogManager.Configuration.Variables["environment"] = "Development";

I have added below filter in my nlog.config file

<rules>
    <logger name="*" minlevel="Error" writeTo="logfile">
        <filters>
            <when condition="equals('${var:environment}', 'Development')" action="Ignore" />                
        </filters>
    </logger>
</rules>

Even though I pass the value as Development, the message is still getting logged instead of ignore.

However, when I hardcoded the value it's working

CodePudding user response:

You have found a bug in NLog, but it should work if you do this (Will also be faster):

<rules>
    <logger name="*" minlevel="Error" writeTo="logfile">
        <filters defaultAction='log'>
            <when condition="'${var:environment}' == 'Development'" action="Ignore" />                
        </filters>
    </logger>
</rules>

Notice you can also use Layout in minLevel. Ex. minLevel="${var:EnvironmentMinLevel:whenEmpty=Error}", which is much faster than <filters>. See also https://github.com/NLog/NLog/wiki/Filtering-log-messages#semi-dynamic-routing-rules

NLog.LogManager.Configuration.Variables["EnvironmentMinLevel"] = "Off";
NLog.LogManager.ReconfigExistingLoggers();
  • Related