How to increase NLog log level at runtime

2.9k Views Asked by At

My application has too much log.Trace() at the beginning of the program, causing the program to malfunction, so I can't use general NLog configuration to increase the log level.

So, I would like to increase the log level at runtime. For that, I've found something like this on the internet:

foreach (var rule in LogManager.Configuration.LoggingRules)
{
    // Iterate over all levels up to and including the target, (re)enabling them.
    for (int i = 0; i <= 5; i++)
    {
        rule.EnableLoggingForLevel(LogLevel.FromOrdinal(i));
    }
}

This, however, seems not to be working as the following line does not show up in the logs, although I'm sure this line has been passed:

log.Trace("log trace works!");

Does anybody know a way to make sure that, from a certain moment in my source code, I can see log.Trace() results?

For your information:

  1. log is defined as private static readonly Logger log = LogManager.GetCurrentClassLogger();.
  2. I've been looking for an nlog.* file, containing an <nlog> tag, I didn't find anything.

Edit:
I'm working with NLog version 4.5.4.

Edit2 (try to force reading of configuration):
I've modified the nlog.config file as follows:

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" autoReload="true">

    <variable name="myLevel" value="Trace" />
    <rules>
      <logger minLevel="${var:myLevel}" />
    </rules>
    ...

Then I tried to force the re-reading of that configuration, as follows:

NLog.LogManager.Setup().LoadConfigurationFromFile("C:\\...\\NLog.config");

Thanks in advance

1

There are 1 best solutions below

1
On BEST ANSWER

Calling LogManager.ReconfigExistingLoggers() after the loop seems to work for me.

Config

<logger name="*" minlevel="Info" writeTo="console" />

Code

logger.Trace("Trace 1");
logger.Info("Info 1");

foreach (var rule in LogManager.Configuration.LoggingRules)
{
    for (var i = 0; i <= 5; i++)
    {
        rule.EnableLoggingForLevel(LogLevel.FromOrdinal(i));
    }
}

LogManager.ReconfigExistingLoggers();

logger.Trace("Trace 2"); // This is now printed.
logger.Info("Info 2");