1

I want to set the log level programmatically. But when I look up my logs, all logs are written (from Trace to Error). I code it like the example on stackoverflow.

foreach (var rule in NLog.LogManager.Configuration.LoggingRules)
{
    //rule.EnableLoggingForLevel(nlogLevel);
    rule.EnableLoggingForLevels(NLog.LogLevel.Warn, NLog.LogLevel.Fatal);
}
NLog.LogManager.ReconfigExistingLoggers();
Logger.LogTrace("LogLevel Trace");
Logger.LogDebug("LogLevel Debug");
Logger.LogInformation("LogLevel Info");
Logger.LogWarning("LogLevel Warn");
Logger.LogError("LogLevel Error");

I tried

rule.EnableLoggingForLevel(nlogLevel); 

and

rule.EnableLoggingForLevels(NLog.LogLevel.Warn, NLog.LogLevel.Fatal);

Screen shot of the log's: enter image description here

Why I can't change the log level?

Frank Mehlhop
  • 1,480
  • 4
  • 25
  • 48

3 Answers3

2

This also happened to me and I was able to solve it by running LogManager.ReconfigExistingLoggers(); after changing log levels.

Juan Alvarez
  • 307
  • 2
  • 5
2

This will work for your case:

rule.SetLoggingLevels(NLog.LogLevel.Warn, NLog.LogLevel.Fatal);

From documentation:

Enables logging the levels between (included) minLevel and maxLevel. All the other levels will be disabled.

ALittleDiff
  • 1,191
  • 1
  • 7
  • 24
1

This is correct, enabling a loglevel doesn't mean disabling another.

Otherwise this will be an issue:

rule.EnableLoggingForLevel(LogLevel.Warn);
rule.EnableLoggingForLevel(LogLevel.Error); // luckily this won't disable Warn

What you could do:

Disable all loglevels first, and then enable the ones you need

rule.DisableLoggingForLevels(LogLevel.Trace, LogLevel.Fatal); // disable all
rule.EnableLoggingForLevels(NLog.LogLevel.Warn, NLog.LogLevel.Fatal); // enable needed

For this case - a minimum for all rules - there is also an easier way:

LogManager.GlobalThreshold = LogLevel.Info; // For all rules, minimum is Info

Please note that it's unclear why all the levels are enabled by default in your code. That's configured in the nlog.config or code, as that is not a default from NLog.

Julian
  • 33,915
  • 22
  • 119
  • 174