12

How do I log inner exception with Log4NET?

This is my current conversion pattern:

<conversionPattern value="%date [%appdomain] %-5level %logger [%property{NDC}] - %message%newline" />
Raj
  • 4,212
  • 11
  • 56
  • 73
  • 1
    Just a note: http://logging.apache.org/log4net/release/sdk/log4net.NDC.html NDC is deprecated. I have successfully used `log4net.ThreadContext.Properties["propertyName"]` instead. Your conversion pattern would be something like `%property{propertyName}` reference:http://logging.apache.org/log4net/release/sdk/log4net.NDC.html – ram Mar 09 '10 at 15:29

3 Answers3

12

Console and File Appenders automatically print the exception. The exception: message, stack trace, and all inner exceptions (again with stack trace) are logged on separate lines and do not follow the conversion pattern.

I am not even sure if you could configure log4net not to print it.

Update: It is possible to configure the appender to not print the stacktrace: Log4Net - Logging out the Exception stacktrace only for certain files

Community
  • 1
  • 1
Stefan Egli
  • 17,000
  • 3
  • 50
  • 72
  • Hi Stefan, Can you point me to a relevant entry in SDK confirming what you answered? – Raj Mar 09 '10 at 15:43
  • I did not read this anywhere. This is what I see in my log files or on the console when I use log4net. Inner exceptions are always printed. – Stefan Egli Mar 09 '10 at 16:54
  • 2
    I don't know why, but I see in my log file just opposite thing - inner exception isn't logged at all. – VikciaR Apr 25 '12 at 13:13
  • are you really sure you have an inner exception? I would not know why log4net should not log it... – Stefan Egli May 05 '12 at 11:58
10

%exception

a formatted form of the exception object in the log entry, if the entry contains an exception; otherwise, this format expression adds nothing to the log entry

Reference: http://www.beefycode.com/post/Log4Net-Tutorial-pt-4-Layouts-and-Patterns.aspx

I believe your exception would contain the inner exception:

Edit: use the ILog.Error() method instead of ILog.ErrorFormat(). As per documentation, ErrorFormat() does not take an Exception object to include in the log event

Lanorkin
  • 6,802
  • 2
  • 34
  • 56
ram
  • 11,033
  • 16
  • 59
  • 86
-1

Just managed to verify this in the sourcecode for Log4Net version 2.0 and I can see there is no consideration for logging InnerException. That is the current limitation of Log4Net (version 2) that it does not support rendering of InnerException out of the box. That's why you would start using NLog as it has builtin support for InnerException rendering - link

dhruvin
  • 697
  • 1
  • 6
  • 11