gpt4 book ai didi

c# - 如何取消订阅 NLog 目标

转载 作者:太空狗 更新时间:2023-10-29 17:48:29 26 4
gpt4 key购买 nike

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

提前致谢。

最佳答案

我不知道为什么 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");
};

//...
}

关于c# - 如何取消订阅 NLog 目标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9724223/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com