Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log4net not logging exception

Tags:

c#

log4net

I have log4net successfully setup for my C# application. Everything works fine, except when I do this:

catch (Exception ex)
{
    if (log.IsErrorEnabled)
       log.Error("test", ex);
}

All I get is the message "test", I do not get the exception at all. Then, when I do this:

catch (Exception ex)
{
    if (log.IsErrorEnabled)
       log.Error(ex);
}

I get the exception as desired, stack trace and everything. This works, but ideally I'd like to have both the message and the exception.

Why does the exact same code (no configuration changes) not work in the first example but it does in the second example? Am I reading the docs wrong for the Error() method?

like image 468
landoncz Avatar asked Sep 28 '22 19:09

landoncz


2 Answers

The first overload you are using is the one that you want: Error(string, Exception). If the exception is actually written depends on your appender and / or the layout you choose. Here is explained how to disable printing of the stacktrace: https://stackoverflow.com/a/3660529/106567

I need to see your configuration in order to tell why the exception is not printed.

The code that "works" is not really what you should do: log.Error(ex) seems to do what you want since log4net treats the exception as the message object and simply calls toString() on it. Any appender / layout that specifically deals with exceptions would be unable to process the exception properly. The same happens if you use one of the ErrorFormat overloads (actually I never quite understood, why you cannot use a formatted string and an exception at the same time).

like image 162
Stefan Egli Avatar answered Oct 19 '22 07:10

Stefan Egli


The solution was not relevant in the code I posted, but I was not fixing the flags correctly. The eventual solution was already found in this stack overflow post

like image 34
landoncz Avatar answered Oct 19 '22 07:10

landoncz