Liordino Neto Liordino Neto - 2 months ago 13
C# Question

NLog - log only one rule from several based on ocurrence of errors

I have the following rules on a NLog.config file:

<rules>
<logger name="*" minlevel="Trace" writeTo="graylog" />
<logger name="*" minlevel="Trace" writeTo="sqlserver" />
<logger name="*" minlevel="Trace" writeTo="xml" />
<logger name="*" minlevel="Trace" writeTo="console" />
</rules>


I want my application to try to log to the first rule, and if it succeeds make this rule final, not logging to anywhere else. If an error occurs (say, the Graylog server is down) it goes on to the second rule, and so on.

Is there any way to make this happen?

Answer

You could use the FallbackGroup for that.

<targets>
  <target xsi:type="FallbackGroup" name="fallbackGroup" returnToFirstOnSuccess="true">
    <target name="graylog" ... />
    <target name="sqlserver" ... />
    <target name="xml" ... />
    <target name="console" ... />
  </target>
</targets>
<rules>
  <logger name="*" minlevel="Trace" writeTo="fallbackGroup" />
</rules>

This will try the first target (graylog) and if it throws an exception, the next target (sqlserver) etc.

See also the docs