Home > Software design >  Why isn't log level changing?
Why isn't log level changing?

Time:09-16

I am attempting to add a function to allow the user to change the logging level. I am running NLog 4.7.11 on .NET 4.5.2. To start here is my nlog configuration:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      internalLogFile="E:\nlog-internal.txt">
  <extensions> 
    <add assembly="NLog.Windows.Forms"/> 
  </extensions> 
  <targets>
    <target name="logfile" xsi:type="File" fileName="program.log" layout="${longdate} | ${level:uppercase=true} | ${message} | ${exception}" />
    <target name="logconsole" xsi:type="Console" />
    <target xsi:type="RichTextBox"
        name="logwindow"
        layout="${longdate} | ${level:uppercase=true} | ${message} | ${exception}"
        autoScroll="true"
        maxLines="500"
        controlName="logTextBox"
        formName="LogWindow"
        useDefaultRowColoringRules="true"
        allowAccessoryFormCreation="false"
        messageRetention="All"
        supportLinks="false">
    </target>
  </targets>

  <rules>
    <logger name="*" minlevel="Warn" writeTo="logconsole" />
    <logger name="*" minlevel="Warn" writeTo="logwindow" />
    <logger name="*" minlevel="Debug" writeTo="logfile" />
  </rules>
</nlog>

I thought the SetLoggingLevels method would make this task fairly easy:

private void logLevelMenuStripItem_Click(object sender, EventArgs e)
{
    logLevelTraceMenuStripItem.Checked = false;
    logLevelInfoMenuStripItem.Checked = false;
    logLevelDebugMenuStripItem.Checked = false;
    logLevelWarnMenuStripItem.Checked = false;
    logLevelErrorMenuStripItem.Checked = false;

    ToolStripMenuItem source = sender as ToolStripMenuItem;

    source.Checked = true;
    LogLevel newLevel = LogLevel.FromString(source.Text);

    foreach (NLog.Config.LoggingRule rule in LogManager.Configuration.LoggingRules)
    {
        rule.SetLoggingLevels(newLevel, LogLevel.Fatal);
    }
}

No matter which value I set with this the rules from my nlog.config are followed. Is there a setting I need to allow programmatic reconfiguration or something else I haven't considered, or have I encountered a bug?

CodePudding user response:

When changing the config, you need to apply it to notify NLog.

E.g.

var config = LogManager.Configuration;

foreach (NLog.Config.LoggingRule rule in config.LoggingRules)
{
    rule.SetLoggingLevels(newLevel, LogLevel.Fatal);
}

// Apply
LogManager.Configuration = config;

See https://github.com/NLog/NLog/wiki/Configure-from-code

There are any way better (read more thread safe) ways to change the configuration runtime. See https://github.com/NLog/NLog/wiki/Configure-from-code#update-config-in-code

  • Related