如何避免 NLog.Config 中的冗余?

How to avoid redundancy in NLog.Config?

目前我在NLog.Config中有以下配置:

<target name="upd" xsi:type="FilteringWrapper" condition="contains('${message}', 'UPD U40') 
        or contains('${message}', 'UPD CAX')
        or contains('${message}', 'UPD CAY')
        or contains('${message}', 'UPD CMVQA')
        or contains('${message}', 'UPD U68')
        or contains('${message}', 'UPD CBY')
        or contains('${message}', 'UPD CBX')
        or contains('${message}', 'UPD CUX')
        or contains('${message}', 'UPD CELL')
        or contains('${message}', 'UPD BPS')
        ">
  <target xsi:type="File" fileName="${basedir}/logs/UPD.log"
          layout="${longdate} - ${message}" />
</target>

<target name="other" xsi:type="FilteringWrapper" condition="not contains('${message}', 'UPD U40') 
        and not contains('${message}', 'UPD CAX')
        and not contains('${message}', 'UPD CAY')
        and not contains('${message}', 'UPD CMVQA')
        and not contains('${message}', 'UPD U68')
        and not contains('${message}', 'UPD CBY')
        and not contains('${message}', 'UPD CBX')
        and not contains('${message}', 'UPD CUX')
        and not contains('${message}', 'UPD CELL')
        and not contains('${message}', 'UPD BPS')
        ">
  <target xsi:type="File" fileName="${basedir}/logs/${shortdate}.log"
          layout="${longdate} - ${message}" />
</target>

...

<logger name="*" minlevel="Debug" writeTo="upd,other"/>

我想要实现的是在 UPD.log 中收集所有 UPD CAX 等模式,而在 ${shortdate}.log 中收集其余模式。我做到了。但是,我认为这里有很大的冗余,因为我必须在两个地方都添加模式。

如何简化 targets/rules 以获得相同的结果?

最简单的简化方法可能是使用变量。您可以将您的条件放入一个变量中,然后切换条件是否为真。如果你想在一个地方配置它们,其他部分如文件路径和布局也可以是变量。这是一个简单的例子:

<variable name="filterCondition" value="contains('${message}', 'UPD U40') 
    or contains('${message}', 'UPD CAX')
    or contains('${message}', 'UPD CAY')
    or contains('${message}', 'UPD CMVQA')
    or contains('${message}', 'UPD U68')
    or contains('${message}', 'UPD CBY')
    or contains('${message}', 'UPD CBX')
    or contains('${message}', 'UPD CUX')
    or contains('${message}', 'UPD CELL')
    or contains('${message}', 'UPD BPS')
    "/>
<variable name="logDir" value="${basedir}/logs" />
<variable name="logLayout" value="${longdate} - ${message}" />

<targets>
  <target name="upd" xsi:type="FilteringWrapper" condition="${filterCondition}">
    <target xsi:type="File" fileName="${logDir}/UPD.log"
      layout="${logLayout}" />
  </target>
  <target name="other" xsi:type="FilteringWrapper" condition="not (${filterCondition})">
    <target xsi:type="File" fileName="${logDir}/${shortdate}.log"
      layout="${logLayout}" />
  </target>
</targets>