Search code examples
c#nlog

NLog: Remove logging rule by name if it was added without name by LoggingConfiguration.AddRule()?


I am new to NLog, but I think I have got a good understand of how it works in the last hours.

After digging deeper into NLog API, several questions about Logging Rules come up. One of them is:
How can I remove a rule by name (using LoggingConfiguration.RemoveRuleByName()) that I have added programmatically by LoggingConfiguration.AddRule() before?

  • LoggingConfiguration.AddRule() does not provide an argument to set the LoggingRule.RuleName.
  • LoggingConfiguration.AddRule() does not take a LoggingRule object.
  • I don't want to check every rule in the LoggingConfiguration.LoggingRules collection, because this would mean checking them by content, because I cannot set a name.

Solution

  • While writing the question, I found the solution, which I want to share here.

    The LoggingConfiguration.LoggingRules collection is a IList<LoggingRule> and thus supports Add(), Clear(), etc.
    Therefore it is possible to add LoggingRule objects directly into this list. The LoggingRule object can be removed again by IList<>.Remove(), and, if it has a name, by LoggingConfiguration.Remove().

    Example for adding named rule:

    var loggingRule1 = new NLog.Config.LoggingRule ();
    loggingRule1.RuleName = nameof (loggingRule1); // RuleName can also be set in constructor.
    loggingRule1.LoggerNamePattern = "*";
    loggingRule1.SetLoggingLevels (NLog.LogLevel.Info, NLog.LogLevel.Error);
    loggingRule1.Targets.Add (consoleTarget);
    loggingConfiguration.LoggingRules.Add (loggingRule1);
    
    var loggingRule2 = new NLog.Config.LoggingRule ("*", NLog.LogLevel.Trace, NLog.LogLevel.Trace, consoleTarget) { RuleName = "loggingRule2" };
    loggingConfiguration.LoggingRules.Add (loggingRule2);
    
    logFactory.ReconfigExistingLoggers ();
    // or, if config was not yet set to logFactory: logFactory.Configuration = loggingConfiguration;
    

    Example for removing named rule:

    loggingConfiguration.RemoveRuleByName (nameof (loggingRule1));
    logFactory.ReconfigExistingLoggers ();
    

    IMHO the API is poorly documented. I will suggest some more comprehensive descriptions.