以编程方式添加,启用和禁用NLog记录器

Sta*_*ker 19 c# nlog

如何从NLog的代码添加,编辑,删除,启用和禁用记录器?

Jon*_*Jon 31

加上:

var logTarget = new ...
logTarget.Layout = "Your layout format here";
// e.g. "${logger}: ${message} ${exception:format=tostring}";

// specify what gets logged to the above target
var loggingRule = new LoggingRule("*", LogLevel.Debug, logTarget);

// add target and rule to configuration
LogManager.Configuration.AddTarget("targetName", logTarget);
LogManager.Configuration.LoggingRules.Add(loggingRule);
LogManager.Configuration.Reload();
Run Code Online (Sandbox Code Playgroud)

去除完成

LogManager.Configuration.LoggingRules.Remove(loggingRule);
LogManager.Configuration.Reload();
Run Code Online (Sandbox Code Playgroud)

  • 我可以看到禁用或启用所有日志的最简单方法:LogManager.EnableLogging()和LogManager.DisableLogging() (5认同)

Duk*_*ets 8

我知道这是一个旧答案,但是我想为任何希望对其目标进行修改并以编程方式记录Configuration.Reload()无法正常工作的规则的人提供反馈。

要以编程方式更新现有目标,您需要使用ReconfigExistingLoggers方法:

var target = (FileTarget)LogManager.Configuration.FindTargetByName("logfile");
target.FileName = "${logDirectory}/file2.txt";
LogManager.ReconfigExistingLoggers();
Run Code Online (Sandbox Code Playgroud)

快速添加和删除日志记录规则的示例:

if (VerboseLogging && !LogManager.Configuration.LoggingRules.Contains(VerboseLoggingRule))
{
    LogManager.Configuration.LoggingRules.Add(VerboseLoggingRule);
    LogManager.ReconfigExistingLoggers();
}
else if (!VerboseLogging && LogManager.Configuration.LoggingRules.Contains(VerboseLoggingRule))
{
    LogManager.Configuration.LoggingRules.Remove(VerboseLoggingRule);
    LogManager.ReconfigExistingLoggers();
}
Run Code Online (Sandbox Code Playgroud)

如文档中所述:

循环遍历以前由GetLogger返回的所有记录器。并重新计算其目标和过滤器列表。在以编程方式修改配置以确保所有记录器均已正确配置之后很有用。

此答案和示例来自Tony的答案:

在运行时更新NLog目标文件名

  • 谢谢你!我花了几个小时试图找出为什么我的配置更改没有传播到我的 Log 对象。恕我直言,NLog 已经变得令人困惑。 (2认同)