如何取消订阅NLog目标

时间:2012-03-15 16:43:11

标签: c# nlog

我希望NLog目标停止收听日志。 RemoveTarget方法似乎不起作用。这是一个失败的测试。

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

提前致谢。

2 个答案:

答案 0 :(得分:10)

我不知道为什么RemoveTarget无效。但是,如果您从每个规则中删除目标,则测试通过:

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

如果您删除了LoggingRule而不是目标,它也会起作用:

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

    //...
}

答案 1 :(得分:1)

NLog版本。 4.5修复了LoggingConfiguration.RemoveTarget,使其从所有已注册的LoggingRules中删除了目标。

另请参阅:https://github.com/NLog/NLog/pull/2549