Exception Handling versus Logging

Exceptions versus Logging

The big question is, when to use logging and when exceptions? Let me tell you a story:

Not so long ago I have been working in a Java project where I introduced log4j, and was very happy to see that all the System.out.println‘s got removed and replaced with the much more sophisticated logging. For a while, life was good. But soon something startet to smell. At first it was a faint scent, and nobody noticed it. Then it got bigger. And bigger. And even bigger.
A huge, unbearable stench: After each run of our application, we accumulated about 20MB of logging messages. Fixing problems became increasingly difficult, even with log4j’s features it was very difficult to locate the source of problems.

We decided that something needed to change. Slowly but surely, we removed most of the logging output and replaced it with exceptions that are thrown but never catched. Oh, what an uproar! Our app crashed all the time. You think that’s bad? It was a blessing! Finally the developers (including me) had a motivation to fix the problems, and in the end the product got a lot more stable and everyone lived happily ever after.

Why is logging bad?

The disadvantage of logging is that it requires user interaction, so it scales very badly. Each logged message has a probability of beeing overlooked, misunderstood, or willingly ignored. Logging requires user interaction, only if somebody is reading the logs you get something out of it.

My Advice

  • Be afraid of logging, be very afraid. It is dangerous, use it only when you have absolutely no other chance. Consider better exception handling, better Unit Tests, or simpler code instead.
  • Although logging is better than writing something to the console, it’s basically the same: nobody will read it anyway, it will be lost in the data nirvana.
  • Fail fast and hard: If you have a problem, crash right away. Make a huge *bang* and stop working. Your customer might not like it when your application crashes sometimes, but crashing is way better than continuing to operate on erronous data, you never know to what that could lead…
  • If you think you need logging for debugging purpose, try to write a Unit Test instead. This might be more difficult, but has the huge advantage of beeing automatable.

Exception Handling Rules

Here some rules of thumb about exception handling:

  • Be Specific – Use as specific exceptions as possible, even if you have to create a new exception subclass. (e.g. throw a ServiceUnavailableException instead of Exception)
  • Throw Early – fail fast, throw as soon as possible. The exception becomes both more specific and more accurate.
  • Catch Late – Never catch an exception you don’t know how to handle. If you can’t actually make things better by catching it, don’t. Let it go up until somebody higher up does.

If you cannot handle an exception and want to avoid the throw-the-kichen-sink antipattern, wrap the exception up and rethrow the wrapped one. For example:

Logging Rules

If you still have to use logging, here are some guidelines when to use which logging level:

  • Fatal – component cannot continue or recover, and is throwing in the towel
  • Error – errors in the component, continuing may be possible
  • Warn – something is not ideal, but I can continue
  • Info – information for the deployer
  • Debug – debugging for the developer, will be removed later

References

26 Comments on "Exception Handling versus Logging"

Notify of
avatar
trackback

Exception Handling versus Logging

trackback

[…] 1 votes […]

pholthuizen
Guest

In my opinion logging is not bad because you have to read logs. Most of the times you have alerts for logged exceptions so people get notified anyway. The decision between logging and throwing has to be based on who you want to bother with the exception: the current user of the application or a third party like a system administrator. The first applies for thrown and catched exceptionns, the latter is more loggin candidate.

Sincerely,
Patrick Holthuizen

hxa7241
Guest

Don’t you mean ‘Exceptions vs Defaults’?

Logging is just a passive view. It doesn’t influence state. And an exceptional state must be reset.

If a pre-/post-condition or invariant fails, there is an exceptional situation. The software *cannot* handle the current state. The two possible remedies are: throw an exception, or use a default. One resumes to a previous legal state, the other replaces the illegal state and continues. (Both can be logged.)

Using defaults *seems* to make the software more fault-tolerant. But throwing exceptions is a more powerful pattern… — and, as the article indicated, raises more of an alarm…

martinus
Guest

I mean that lots of people think of logging as error handling. They throw an exception if something bad happens, and somewhere else they catch it and all they do is write a log message and continue as if nothing has happend. This has caused me a lot of headage.

tonetheman
Guest

logging might be evil but it you are writing and running an application that actually needs to stay up all the time. failing hard and fast is not always the best choice.

logging has always been a fine way to debug. if your logs are growing too large then you need to add levels to show just errors and criticals.

in some cases it is the only way to debug, like in a real production environment

Mike
Guest

My biggest problem with logging is libraries that force a logging toolkit on you. Libraries should throw exceptions. The first thing I do when I want to use an open source library is rip out Log4J and make it throw exceptions.

Sure, I understand the library developers need logging to debug. However, I propose a novel solution. Write a test application that uses your library and make it catch the exceptions and log them. No logging needed in the library code that way!

fakemail@example.com
Guest
Why should it one or the other? You can use both logging and throwing exceptions. I use both in my code. Just before throwing exception, I logg the details. This ensures that I have a persistent record that I can go back to and check for details. This is important “evidence” while debugging an issue – why throw it away? OK, unnecessary logging is evil – you need “smart” log messages. Just logging everything is a strict “no-no”. Every log message should add “value” or else logging it is a waste of time. Regards, Mahesh PS : Sorry – I… Read more »
leefw
Guest

Not sure what type of application you are refering to here, but at least for many server-side applications logging is all there is! As an administrator I would have no clue where to start if the developers didn’t give me some kind of hint (preferably text based) to what went wrong shoud their application die. I don’t disagree with you regarding exception handling, but I think this may be a case of comparing apples and oranges. Logging and exception handling work very well together.

Tbee
Guest

Logging is required to determine how the exception came to be; logging describes the path, the exception the result.

martinus
Guest

@Tbee: Exceptions themself have the stack trace, so you don’t need logging to describe the path. I think logging is somewhat similar to the GOTO statement. Mostly it is missused, but in rare cases it is useful. Logging is just sugar coating your problem. Nothing helps you squash bugs more than a descriptive exception that crashes the whole application 🙂

Brian Clear
Guest

On our website we have error handlers on our site that email us immediately if an error occurs on a page. It emails the whole team including our boss but to the user it degrades gently with a helpful error message. I think crashing and expecting the customer to ring up and complain wont work. Customers will just go “this site is rubbish I’m off elsewhere”.

Tbee
Guest

@martinus: the stacktrace only describes where the result occured, not how the result came to be. It is of course possible do deduce the programflow, but if there are multiple paths, an exception does not suffice.

Naturally it is hard to solve a problem without a good description (=exception). So my statement was not intended to say that the exception is useless, far off even, but that logging and exception are complementary.

The article states that logging is bad, and with that I absolutely do not agree. But good exceptions are equally important.

Tbee
Guest

Let me illustrate:

if (x) y();
z();

Suppose the exception occured somewhere deep within z(), the exception cannot tell you if y() was also executed. You have to try and deduce that, or enable logging and check the output.

trackback

[…] Exception Handling versus Logging […]

kawazu
Guest
You don’t really just use logging as a debugging facility, do you? If so, you’re surely right – using an exception system as provided by Java surely is likely to help you here (after all, that’s what it is there for). But log4j and logging in general is a good thing for situations where you don’t worry about your code running wild but just about, say, tracking the behaviour of your system in real-life operation. I want to know if someone tried to login to my application using the wrong password and/or an unregistered user name. I want to see… Read more »
martinus
Guest

@kawazu, your example with the wrong password is very good, that’s where logging makes perfectly sense.

Anonymous
Guest

One real problem with logging is when you have a server based application with 400 concurrent users and 50 of them hit a bug during a given period of time, the same Exception (including a stack trace) is logged 50 times. To get round this would need some interesting code in the exceptions to detect if it has been logged already and only put out a basic message for subsequent occurances.

Gwyn Evans
Guest

Sounds to me as if you didn’t filter your logging to differentiate between levels, e.g. Fatal, Error, Warn, Info & Debug. If you do that, you’d be able to focus in the real issues, maybe by logging just the Fatal & Errors to one location for monitoring while logging all the supporting (lower level) info elsewhere for reference on a case by case basis.

Ravi Yagatili
Guest
Exception handling is how your application responds when for example your application’s backend system or the service is unavailable and how you handle it., where as logging information from your application (responsibly using different levels available within log4j), gives you information about your application for the various interactions and how much of that information makes sense to you and how you would interpret your application. If you log unneccessary information that you do not need & then you enable it in a production environment then obviously you are thrashing your application & abusing the logging. If on the other hand… Read more »
Anonymous
Guest

Logging is useful. But as you stated, if nobody looks at them, they’re useless.
See LogDistiller (http://logdistiller.sourceforge.net/), a GPL tools to help automatically classifying logs so that they become usefull, without too much work

trackback

[…] or anything else: What are your experiences with logging? // posted by NotesTracker @ 6/28/2006 12:08:00 PM    Comments: Post a Comment Links to this post: See links to this post   posted by @ if (typeof BL_addOnLoadEvent == ‘function’) { BL_addOnLoadEvent(function() { BL_writeBacklinks(); }); } […]

trackback

[…] Exception Handling versus Logging […]

richard
Guest

Hi,

The production systems we put together are set up so that uncaught exceptions are emailed to support programmers. Getting emailed all the time is pretty annoying and is good motivation for fixing the bugs. The users just see a message such as ‘An error occurred and support staff are working on resolving the problem now’.

trackback

[…] Exception Handling versus Logging < Programming Kung Fu […]

Anonymous
Guest
My advice 1. Never ever expect a customer to tolerate downtime, you WILL get shouted at if this happens often and potentially get sued! 2. Test your software properly on a test machine before it goes live, to stop an avoidable flood of live errors, log4J will help loads here! 3. Actively design how your logging works, don’t just throw in logging statement, use just enough logging at key points in the code, with the correct logging levels 4. Log4j is a very powerful API, but must be use correctly to be useful e.g. it can support multiple filters, appends… Read more »
wpDiscuz