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.
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");
};
//...
}
NLog ver. 4.5 fixes LoggingConfiguration.RemoveTarget
so it removes target from all registered LoggingRules.
See also: https://github.com/NLog/NLog/pull/2549
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With