Logging Inner Exceptions with NLog

Most of the time while logging exceptions, we log ex.Message or ex.Message + ex.StackTrace. However, in this way, inner exceptions are left out.

NLog provides its own way of logging exceptions and it can log inner exceptions up to any level we want. Below is an example of logging exceptions with NLog.

In your code just log the exception object:

try
{
    ProcessItems();
}
catch (Exception ex)
{
    logger.Error(ex, “Your exception message here”);
}

In NLog.config, configure the layout like this:

<target xsi:type="File"
  name="f"
  fileName="${basedir}/logs/MyLogFile.log"
  layout="${longdate} ${uppercase:${level}} ${message} ${exception:format=Message,StackTrace,Data:maxInnerExceptionLevel=10}"
/>

If you want, you can also add archiving:

<target xsi:type="File"
  name="f"
  fileName="${basedir}/logs/MyLogFile.log"
  layout="${longdate} ${uppercase:${level}} ${message} ${exception:format=Message,StackTrace,Data:maxInnerExceptionLevel=10}"
  archiveEvery="Day"
  archiveNumbering = "Date"
  archiveFileName="${basedir}/logs/MyLogFile.{#}.log"
  archiveDateFormat="yyyyMMddHHmm"
  maxArchiveFiles="15"
/>

The above configuration will generate log file with a particular name inside logs folder. However, you can also append date time in log file name.

The result will be like this in the log file:

2018-11-29 10:11:34.4148 ERROR System.Exception: This is the message coming from outer exception ---> System.Net.WebException: The remote name could not be resolved: 'test-server'
   at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
   at System.Net.HttpWebRequest.GetRequestStream()
   at Microsoft.SharePoint.Client.SPWebRequestExecutor.GetRequestStream()
   at Microsoft.SharePoint.Client.ClientContext.GetFormDigestInfoPrivate()
   at Microsoft.SharePoint.Client.ClientContext.EnsureFormDigest()
   at Microsoft.SharePoint.Client.ClientContext.ExecuteQuery()
   at Common.Library.ProcessItems() in D:\Repos\poc\Library.cs:line 79
   --- End of inner exception stack trace ---
   at Common.Library.ProcessItems() in D:\Repos\poc\Library.cs:line 183
   at Common.Library.Process() in D:\Repos\poc\Program.cs:line 46

 

Leave a comment