我正在使用带有配置文件的NLog。为了避免为某些长时间处理记录太多东西,我正在做这样的事情:
foreach (LoggingRule rule in LogManager.Configuration.LoggingRules)
{
rule.DisableLoggingForLevel(LogLevel.Trace);
rule.DisableLoggingForLevel(LogLevel.Debug);
}
LogManager.ReconfigExistingLoggers();
它允许我临时降低日志记录详细级别。上面的行只是为了说明而已。
之后,我想通过重新加载已在程序启动时自动加载的NLog.Config文件来恢复我的“常规”日志记录配置。
LogManager.Configuration.Reload();
LogManager.ReconfigExistingLoggers();
我认为这很简单,但configuration.Reload并没有达到我的期望,我也没有找到其他合适的方法。在调用之后,我的记录器仍然没有存储跟踪和调试事件,而它们在程序启动时是存在的。
所以我的问题是:如何在运行时以编程方式强制重新加载NLog.config,并恢复我的“标准”记录器设置?
谢谢
更多详细信息更新的问题:
我正在使用VS2013,.Net 4项目,使用NLog 4.4.0-beta11(nuget上的最新beta版),配置文件中定义了简单的“File”目标,minLevel = Trace,autoReload=True Logger在类级别被实例化: private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
以下是我的测试证据:
Assert.True(Logger.IsTraceEnabled);
Assert.True(Logger.IsDebugEnabled);
Logger.Trace("1 - This should appear in log");
Logger.Debug("2 - This should appear in log");
foreach (LoggingRule rule in LogManager.Configuration.LoggingRules)
{
rule.DisableLoggingForLevel(LogLevel.Trace);
rule.DisableLoggingForLevel(LogLevel.Debug);
}
LogManager.ReconfigExistingLoggers();
Logger.Trace("3 - This should NOT appear in log");
Logger.Debug("4 - This should NOT appear in log");
Logger.Info("5 - This should appear in log");
Assert.False(Logger.IsDebugEnabled);
Assert.False(Logger.IsTraceEnabled);
LogManager.Configuration.Reload();
LogManager.ReconfigExistingLoggers();
// This is were something goes wrong
Logger.Trace("6 - This should appear in log"); // DOES NOTHING
Logger.Debug("7 - This should appear in log"); // DOES NOTHING
Logger.Info("8 - This should appear in log");
Assert.True(Logger.IsDebugEnabled); // FAILS
Assert.True(Logger.IsTraceEnabled); // FAILS
生成的日志:
TRACE 1 - This should appear in log
DEBUG 2 - This should appear in log
INFO 5 - This should appear in log
INFO 8 - This should appear in log
在nlog的内部日志中,我可以看到配置似乎已经被重新加载,没有问题(文件很长,所以我不会在这里发布,除非有人要求),但现有的记录器可能没有更新?
使用上面的代码应该很容易在您的一侧尝试。如果我做错了什么或者这是NLog配置管理中的一个错误,请告诉我。