使用 NLog 仅将错误记录到 StdErr 输出流

Log only Errors to StdErr Output Stream with NLog

NLog 支持将 error="true" 键值对添加到 target XML 节点,如下所述:https://github.com/NLog/NLog/wiki/Console-target

但是,我注意到这会将所有日志输出到 StandardError 流,而不仅仅是 Error 级别的日志。

例如,当我添加 error="true" 键值对时,这两行日志都将转到 stderr:

logger.Info("This should not go to stderr... but it does!");
logger.Error("This works!");

如何让 NLog 只输出错误到 st​​derr 流,而不是所有日志?

为了完整起见,这是我的 NLog.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">

  <targets>
    <target name="logconsole" xsi:type="Console" error="true" />
  </targets>

  <rules>
    <logger name="*" minlevel="Info" writeTo="logconsole" />
  </rules>
</nlog>

对于 error="true",所有发往该目标的消息都将发送到错误流。

仅针对错误事件, 你需要两个目标;一个用于错误流和 non-error 流。使用两条规则,您可以将事件发送到正确的目标。

例如:

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

  <targets>
    <target name="logconsoleError" xsi:type="Console" error="true" />
    <target name="logconsole" xsi:type="Console" />
  </targets>

  <rules>
    <logger name="*" minlevel="Error" writeTo="logconsoleError" final="true" />
    <logger name="*" minlevel="Info" writeTo="logconsole" />
  </rules>
</nlog>

请注意我在这里使用 final 属性,否则信息和警告日志将发送到两个目标。