如何配置 "when" 条件 NLog 规则?

How do configure "when" conditional NLog rules?

我正在尝试记录条件 NLog。我总是传递一个字符串(在本例中为 Rule1 或 Rule2),指定什么规则作为消息的第一部分。

我的问题是,根据下面的当前规则,两个规则都被标记为 "true" 和日志文件。我不明白这怎么可能。我在这个例子中使用了 "Rule1" 和 "Rule2" 的字符串,但是实际传递的字符串是完全不同的(不是同一个单词不同的数字)。

传递给记录的示例消息是...

Ex1: ${message} = "Rule1,Information about the rule,foo

示例 2:${message} = "Rule2,Information about the other rule,bar

这是我的示例目标

<!-- language: config -->
<?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="false"
  internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log"
  keepVariablesOnReload="true">

  <variable name="dir_Logging" value="C:/<myPath>"/>
  <variable name="dir_Archive_Rule1" value="${dir_Logging}/Log Archives/Rule1/${shortdate}"/>
  <variable name="dir_Archive_Rule2" value="${dir_Logging}/Log Archives/Rule2/${shortdate}"/>
  <variable name="varRule1" value="Rule1"/>
  <variable name="varRule2" value="Rule2"/>

  <targets>
    <target xsi:type="File" name="rule1Logs"
      archiveOldFileOnStartup="true"
      archiveNumbering="Date"
      archiveDateFormat="yyyy-MM-dd_HH-mm-ss"
      fileName="${dir_Logging}/Logs - Rule1.csv"
      archiveFileName="${dir_Archive_Rule1}/Logs - Rule1.{#}.csv">
        <layout xsi:type="SimpleLayout"
          text="&quot;${date:format= yyyy/MM/dd}&quot;,&quot;${date:format= HH\:mm\:ss.fff}&quot;,${message}"/>
    </target>
    <target xsi:type="File" name="rule2Logs"
      archiveOldFileOnStartup="true"
      archiveNumbering="Date"
      archiveDateFormat="yyyy-MM-dd_HH-mm-ss"
      fileName="${dir_Logging}/Logs - Rule2.csv"
      archiveFileName="${dir_Archive_Rule2}/Logs - Rule2.{#}.csv">
        <layout xsi:type="SimpleLayout"
          text="&quot;${date:format= yyyy/MM/dd}&quot;,&quot;${date:format= HH\:mm\:ss.fff}&quot;,${message}"/>
    </target>
  </targets>

  <rules>
    <logger name="*" level="Info" writeTo="rule1Logs">
      <filters>
        <when condition="starts-with('${message}','${varRule1}')" action="Log"/>
      </filters>
    </logger>
    <logger name="*" level="Info" writeTo="rule2logs">
      <filters>
        <when condition="starts-with('${message}','${varRule2}')" action="Log"/>
      </filters>
    </logger>
  </rules>

过滤器的默认值是 "neutral",因此如果它与您的过滤器不匹配,它就会被记录下来。

这是一个known limitation and will be addressed in NLog 4.6 (See code change in NLog 4.6)

现在您需要:

  1. 反转条件并action=ignore
  2. 或者,添加第二个忽略所有的过滤器