Skip to content

How to Log Exceptions

Rolf Kristensen edited this page Mar 15, 2023 · 10 revisions

Exceptions require special treatment in NLog. You need to call the method on the Logger class which takes an Exception as its first argument. The method name matches the log level. For instance, to log an exception using the Error loglevel, do:

logger.Error(ex, "Oops, an exception occured");

Please note: the methods have been changed in NLog 4.0. Previous versions expected the exception after the message.

Example

You typically log exceptions inside a catch handler. An example of logging an exception with the Error LogLevel is seen in the following:

try 
{ 
    // some code which may throw 
} 
catch (MyException ex) 
{ 
    logger.Error(ex, "Got exception.");  // NLog 4.0 and newer
    logger.Error("Got exception.", ex);  // Before NLog 4.0, and now obsolete
}

Exception Formatting

To write the details of the exception, use the ${exception} in your layout. Depending on the desired output you may want to specify different value for the format argument. The following example displays the result of calling ToString() on the exception object.

<nlog> 
  <targets> 
    <target name="f" type="File" 
            layout="${longdate} ${message} ${exception:format=tostring}"/> 
  </targets> 
  <rules> 
    <logger name="*" writeTo="f"/> 
  </rules> 
</nlog>

For simpler scenarios you may directly use the ${message:withException=true}, which is used in the default Layout in NLog v5.0:

<nlog> 
  <targets> 
    <target name="f" type="File" 
            layout="${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}"/> 
  </targets> 
  <rules> 
    <logger name="*" writeTo="f"/> 
  </rules> 
</nlog>
Clone this wiki locally