这是我的 NLog.config,我在其中定义了一个变量。logLevelMaxLength
:
<?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"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="true"
internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
<variable name="logLevelMaxLength" value="20" />
<targets>
<target name="logfile" xsi:type="File" fileName="logfile.log" layout="${longdate}|${pad:padding=${logLevelMaxLength}:inner=${level:uppercase=true}}|${logger}|${message}" />
<target name="logconsole" xsi:type="Console" />
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="logconsole" />
<logger name="*" minlevel="Trace" writeTo="logfile" />
</rules>
</nlog>
我正在使用该变量值来填充日志中的级别打印。但在我的代码中,我更新了该值,并试图让日志打印使用新的值来填充。
MessageBox.Show(LogManager.Configuration.Variables["logLevelMaxLength"].ToString()); //Shows old value: 20
LogManager.Configuration.Variables["logLevelMaxLength"] = "10";
MessageBox.Show(LogManager.Configuration.Variables["logLevelMaxLength"].ToString()); //Shows new value: 10
我可以通过编程更改该值,并通过MessageBox确认更改,但打印的日志仍然使用旧值进行打印。我甚至尝试使用 LogManager.ReconfigExistingLoggers();
命令,但没有任何帮助。我到底做错了什么?
当使用 ${logLevelMaxLength}
的值不能在运行时更改。如果你需要这样做,使用这个语法。 ${var:logLevelMaxLength}
在配置文件中直接使用 NLog 变量时,性能会更好(例如:在配置文件中使用 NLog 变量),而不是使用这个总是执行动态查找的布局渲染器(例如:在配置文件中使用 NLog 变量)。
${myvar}
),而不是使用这个总是执行动态查找的布局渲染器(Ex.${var:myvar}
). 但这个布局渲染器会在运行时对修改的 NLog 变量做出反应。
不幸的是,${pad}的padding属性不是可布局的(它不属于Layout类型),所以你不能使用动态值。
有多种解决方案。