c# - Why isn't log level changing?
问题描述
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?
解决方案
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
推荐阅读
- c# - 使用 linq any 检查列表中是否包含
- python - Pandas - 在多列上使用`.rolling()`
- sql - SQL server 中的 Oracle Connect_is_leaf 类似
- mysql - 在mysql数据库中查找最长的连续系列
- wso2 - wso2 5.0.0 jms activemq consummer.exclusive
- sql - 保存查询结果而不将其附加到 PostgreSQL 中的现有表中
- hybris - 订单表的 Hybris 后台搜索
- sonarqube - 未检测到 SonarQube 规则
- python - python为线性回归指定权重
- react-native - 用特殊字符反应本机问题