try
{
// Code
}
catch (Exception ex)
{
Logger.Log("Message", ex);
throw;
}
In the case of a library, should I even log the exception? Should I just throw it and allow the application to log it? My concern is that if I log the exception in the library, there will be many duplicates (because the library layer will log it, the application layer will log it, and anything in between), but if I don’t log it in the library, it’ll be hard to track down bugs. Is there a best practices for this?
I would not log an exception that I wasn’t going to do anything with – ie, if it’s just passing through an exception handler as in your example. As you already mentioned, this adds a lot of noise that isn’t necessarily helpful. Better to log it at the point where you are actually doing something about it, or, in the case of a library, at the boundary where it transitions into the user’s code.
That said, I always try to log at the point where I am throwing the exception and the condition that triggered the exception. This is much more useful to pin down the reason for the exception; plus, if the condition that you encounter is bad enough to warrant throwing an exception, I would say it also warrants spending the processor time logging out the ‘why’.