10

I want a NLog target to stop listening to the log. The RemoveTarget method doesn't seem to work. Here is a failing test.

public class when_stopping_to_listen
{
    static Logger Logger;
    static MemoryTarget target;

    Establish context = () =>
    {
        var config = new LoggingConfiguration();
        Logger = LogManager.GetLogger("TestLogger");

        target = new MemoryTarget {Layout = "${message}", Name = "TestTarget"};

        config.AddTarget(target.Name, target);
        config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, target));

        LogManager.Configuration = config;
    };

    Because of = () =>
    {
        var config = LogManager.Configuration;
        config.RemoveTarget(target.Name);
        LogManager.Configuration = config;
        Logger.Info("Test");
    };

    It should_be_empty = () => target.Logs.ShouldBeEmpty();
}

Thanks in advance.

forki23
  • 2,784
  • 1
  • 28
  • 42

2 Answers2

11

I don't know why RemoveTarget doesn't work. But if you remove the target from each rule the test passes:

Because of = () =>
{
    foreach (var rule in config.LoggingRules)
    {
        rule.Targets.Remove(target);
    }        
    Logger.Info("Test");
};

And if you remove the LoggingRule instead of the target it also works:

public class when_stopping_to_listen
{
    //...
    static LoggingRule rule;

    Establish context = () =>
    {
        //...
        rule = new LoggingRule("*", LogLevel.Trace, target);
        config.LoggingRules.Add(rule);    
        LogManager.Configuration = config;
    };

    Because of = () =>
    {
        var config = LogManager.Configuration;
        config.LoggingRules.Remove(rule);
        LogManager.Configuration = config;
        Logger.Info("Test");
    };      

    //...
}
nemesv
  • 138,284
  • 16
  • 416
  • 359
  • 3
    It seems so... From the Nlog's source code it seems once it's initialized the rules with the targets it doesn't uses the `LogManager.Configuration.ConfiguredNamedTargets` collection any more. That's why the `RemoveTarget` isn't working. – nemesv Mar 15 '12 at 19:38
1

NLog ver. 4.5 fixes LoggingConfiguration.RemoveTarget so it removes target from all registered LoggingRules.

See also: https://github.com/NLog/NLog/pull/2549

Rolf Kristensen
  • 17,785
  • 1
  • 51
  • 70