NLog只在Debug模式输出log

2020年4月8日 0 作者 老王

  1.首先是NLog.config配置文件中需要在rules中添加filters,如下

<target xsi:type="AsyncWrapper" name="asyncProd">
  <target xsi:type="File" name="logfileProc" fileName="${basedir}/logs/${buildConfiguration}.log"/>
</target>

<rules>
    <logger name="*" minlevel="Info" writeTo="asyncProd">
      <filters>
        <when condition="equals('${buildConfiguration}','Debug')" action="Ignore" />
      </filters>
    </logger>
</rules>

  2.然后添加个BuildConfigLayoutRenderer脚本

[LayoutRenderer("buildConfiguration")]
[ThreadAgnostic]
public class BuildConfigLayoutRenderer : LayoutRenderer
{
    private String buildconfig;
    private String GetBuildConfig()
    {
        if (buildconfig != null)
        {
            return buildconfig;
        }

        #if DEBUG
            buildconfig = "Debug";
        #else
            buildconfig = "Release";
        #endif
            return buildconfig;
    }

    protected override void Append(StringBuilder builder, LogEventInfo logEvent)
    {
        builder.Append(GetBuildConfig());
    }
}

  3.最后在Main方法调用如下语句。

LayoutRenderer.Register<BuildConfigLayoutRenderer>("buildConfiguration");

  搞定。
  参考博客:
https://stackoverflow.com/questions/26846553/nlog-only-log-while-debugging