NLog Inner Exception Logging
Asked Answered
H

2

14

I'm trying to log inner exception messages by using NLog. This is a piece of my NLog.config file:

<target name="errors" xsi:type="File" layout="${longdate}${newline}
    - Exception Message: ${exception:format=Message}${newline}
    - InnerException Message: ${exception:innerExceptionSeparator=TEXT}${newline}"
   fileName="\Logs\errors-${shortdate}.log"
   concurrentWrites="true" />
</targets>

I'm getting the same message See the inner exception for detailsfor both Exception Message and InnerException Message lines of NLog.config file.

Hoagland answered 31/5, 2017 at 14:28 Comment(0)
H
21

This worked for me:

  <target name="errors" xsi:type="File" layout="
            ${message}
            ${onexception:EXCEPTION OCCURRED\:
            ${exception:format=type,message,method:maxInnerExceptionLevel=5:innerFormat=shortType,message,method}}"
            fileName="\Logs\errors-${shortdate}.log"
            concurrentWrites="true"
            />
  </targets>

Property descriptions :

  • ${exception:maxInnerExceptionLevel=N} - controls how many inner exceptions are logged. defaults to zero for backwards compatibility.
  • ${exception:innerExceptionSeparator=TEXT} - defines text that separates inner exceptions. Defaults to new line string (platform specific).
  • ${exception:innerFormat=FORMATSTRING} - defines the format of inner exceptions the same way that ${exception:format=FORMATSTRING} defines the format of the top-level exception. If this parameter is not specified, the same format is used for both top-level and inner exceptions.

Here is the official Nlog Documentation for logging inner exceptions

Hoagland answered 31/5, 2017 at 14:40 Comment(1)
layout in several lines causes log messages to be started not from the leftmost position in console window, the same is for file. Spaces (tabs) between ${message} and line start are shown in the logAstrix
A
7

another possibility is to add new line between inner exception is to use linebreak &#xD;&#xA in the xml, since innerExceptionSeparator is not parsed in some special way and is loaded as it is written. So innerExceptionSeparator=${newline} will not work.

layout="${message}${onexception:${newline}${exception:maxInnerExceptionLevel=10:innerExceptionSeparator=&#xD;&#xA;&#x9;:format=shortType,message}} 

this will cause inner exception text to be started from the new line and indented by tab character

however this works only if ILogger.Error(Exception, string) method is used. ILogger.Error(Exception) ignores this layout

Astrix answered 4/10, 2017 at 9:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.