0
votes

Based on the answer here: How Thread-Safe is NLog? I have created a Logger and added two MappedDiagnosticsContext to NLog:

NLog.MappedDiagnosticsContext.Set("Module", string.Format("{0}.{1}", module.ComputerName, module.ModuleType));
NLog.MappedDiagnosticsContext.Set("ModuleCoreLogLevel", string.Format("LogLevel.{0}", module.CoreLogLevel));

I can successfully use the "Module" Context in the NLog config (programmatically) to generate the file name the logger should log to:

${{when:when=length('${{mdc:Module}}') == 0:inner=UNSPECIFIED}}${{when:when=length('${{mdc:Module}}') > 0:inner=${{mdc:Module}}}}.txt

This logs e.g. all messages with a "Module" context of "Test" to a filename called Module.txt

I now want to be able to set the LogLevel for the different Modules using this way, and only Log messages which correspond to this LogLevel (or higher)

I am trying to do this through filters, this means, on the LoggingRule I am trying to add a filter:

rule92.Filters.Add(new ConditionBasedFilter { Condition = "(level < '${mdc:ModuleCoreLogLevel}')", Action = FilterResult.IgnoreFinal });

This however does not seem to filter messages. If I have for example a message which is emitted using Logger.Trace(), and the LogLevel on "ModuleCoreLogLevel" is set to LogLevel.Debug, I can still the Message in the resulting LogFile.

1
I think I solved this by doing this for each level: rule92.Filters.Add(new ConditionBasedFilter { Condition = "(equals('${mdc:ModuleCoreLogLevel}', 'LogLevel.Trace') and level < LogLevel.Trace)", Action = FilterResult.IgnoreFinal }); Anyone better / faster ideas? :)MichelZ

1 Answers

0
votes

I solved this by doing this for each level:

rule92.Filters.Add(new ConditionBasedFilter { Condition = "(equals('${mdc:ModuleCoreLogLevel}', 'LogLevel.Trace') and level < LogLevel.Trace)", Action = FilterResult.IgnoreFinal });