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

时间:2016-08-06 18:02:18

标签: c# nlog

目前我在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 CAX中收集所有UPD.log等模式,其余模式在${shortdate}.log中收集。我做到了。但是,我认为这里存在很大的冗余,因为我必须在两个地方添加模式。

如何简化目标/规则以达到相同的效果?

1 个答案:

答案 0 :(得分:1)

最简单的简化方法可能是使用变量。您可以将条件置于变量中,然后打开条件是否为真。如果要在一个位置配置它们,文件路径和布局等其他部分也可以是变量。这是一个简单的例子:

<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>