Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I unsubscribe a NLog target

Tags:

c#

nlog

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.

like image 615
forki23 Avatar asked Mar 15 '12 16:03

forki23


2 Answers

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");
    };      

    //...
}
like image 150
nemesv Avatar answered Oct 09 '22 10:10

nemesv


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

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

like image 29
Rolf Kristensen Avatar answered Oct 09 '22 10:10

Rolf Kristensen