NLog 教程页面上给出了一个程序化的初始设置示例,我将其包含在下面。(这里有一个更广泛的版本。)
public static void Startup()
{
var config = new NLog.Config.LoggingConfiguration();
// Targets where to log to: File and Console
var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "file.txt" };
var logconsole = new NLog.Targets.ConsoleTarget("logconsole");
// Rules for mapping loggers to targets
config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);
config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
// Apply config
NLog.LogManager.Configuration = config;
LogManager.ReconfigExistingLoggers();
}
然后,要更改日志级别,logconsole
您要更改的目标在哪里:
public static void SetConsoleLogLevel(LogLevel level)
{
foreach (var rule in LogManager.Configuration.LoggingRules)
{
foreach (var ruleTarget in rule.Targets)
{
if (ruleTarget != logconsole) continue;
DisableLoggingForLevels(rule, LogLevel.Trace, level);
rule.EnableLoggingForLevels(level, LogLevel.Fatal);
LogManager.GetCurrentClassLogger().Log(level, "Changed logger level to {0}", level);
}
}
LogManager.ReconfigExistingLoggers();
}
whereDisableLoggingForLevels
是一个私有方法,NLog.Config.LoggingRule.EnableLoggingForLevels
除了它禁用:
private static void DisableLoggingForLevels(LoggingRule rule, LogLevel minLevel, LogLevel maxLevel)
{
for (var ordinal = minLevel.Ordinal; ordinal <= maxLevel.Ordinal; ++ordinal)
rule.DisableLoggingForLevel(LogLevel.FromOrdinal(ordinal));
}