Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to log exception?

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?

like image 740
Rune Avatar asked Apr 04 '10 14:04

Rune


People also ask

Should all exceptions be logged?

Definitely not. You should find the correct place to handle the exception (actually do something, like catch-and-not-rethrow), and then log it. You can and should include the entire stack trace of course, but following your suggestion would litter the code with try-catch blocks.

Should you log before throwing exception?

Log it when you handle it So, better only log the exception when you handle it. Like in the following code snippet. The doSomething method throws the exception. The doMore method just specifies it because the developer doesn't have enough information to handle it.

What is a log exception?

The exception log is a rolling collection of 4 files; when a file is full, data is added to the next file. When the last file has been filled, data starts to be added to the first file, overwriting the previous data there. This cycle of writing continues, ensuring that the newest data is retained.

Why do we Rethrow exceptions?

THE MAIN REASON of re-throwing exceptions is to leave Call Stack untouched, so you can get more complete picture of what happens and calls sequence.


1 Answers

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'.

like image 107
Timo Geusch Avatar answered Sep 22 '22 00:09

Timo Geusch