nlog

log4net to nlog transition: how quickly switch between log levels for logging rules


We started transitioning from log4net to NLog, and I want to clarify something.

In log4net, you have a configuration with appenders and loggers. You skip the appenders and start with the 'root' logger. The configuration looks something like this:

<root>
  <level value="INFO" />
  <appender-ref ref="LogFileAppender" />
</root>

Then, you can simply write the logger name with the log level of 'DEBUG', and it will still be written to the LogFileAppender, despite the 'root' level being set to 'INFO'. For example:

<logger name="SomeClass">
  <level value="DEBUG" />
</logger>

We have become accustomed to this functionality and find it very convenient. It allows us to easily activate DEBUG logging for specific classes while keeping all others at the INFO level.

To simulate a similar behavior in NLog, I came up with the following configuration:

<logger name="SomeClass" finalMinLevel="Info" />
<logger name="SomeClass2" finalMinLevel="Warn" />
<logger name="*" minlevel="Info" writeTo="logfile" />

Now, if I want to enable DEBUG logging for 'SomeClass', I change the rule for 'SomeClass' to this:

<logger name="SomeClass" level="Debug" writeTo="logfile" />

However, this approach requires a lot of typing, especially when I need to switch off the DEBUG level again.

So, what is the best way to achieve such simple switches? Perhaps my NLog configuration is still influenced by log4net, and there is a better way to do it?


Solution

  • Since you are using finalMinLevel in NLog v5 then I guess you can do this:

    <rules>
    <logger name="*" finalMinLevel="Info" />           <!-- Default LogLevel -->
    <logger name="SomeClass" finalMinLevel="Debug" />  <!-- Override LogLevel -->
    <logger name="SomeClass2" finalMinLevel="Warn" />  <!-- Override LogLevel -->
    <logger name="*" writeTo="logfile" />              <!-- Default targets -->
    </rules>
    

    Where the first rule defines the default loglevel for all loggers, which then can be overridden by the following rules.

    And the last rule defines the output for all loggers.

    See also: https://github.com/NLog/NLog/wiki/Logging-Rules-FinalMinLevel