2

NLog supports adding the error="true" key-value pair to the target XML node as documented here: https://github.com/NLog/NLog/wiki/Console-target

However, I notice this outputs all logs to the StandardError stream, not just Error level logs.

For example, both of these log lines will go to stderr when I add the error="true" key-value pair:

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

How can I make NLog only output errors to the stderr stream, not all logs?

For completeness, this is my 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>
Julian
  • 33,915
  • 22
  • 119
  • 174
user1477388
  • 20,790
  • 32
  • 144
  • 264

1 Answers1

3

With error="true" all messages to that target will be send to the error stream.

For only the error events, You need two targets; one for the error stream and for the non-error stream. With two rules you could send the events to the right target.

For example:

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

Please note I use here the final attribute, otherwise info and warn logs will be send to both targets.

Julian
  • 33,915
  • 22
  • 119
  • 174