Routine Java Logging

Java has contained a perfectly satisfactory logging system for some time, in java.util.logging.*

Most use of the package still seems careless and casual, even in large systems. Here are some simple rules I follow.

First, I scope loggers by the fully qualified classname. I put this boilerplate at the top of every class that may need logging.
import java.util.logging.Logger;

public class Foo {
  @SuppressWarnings("unused") private static final Logger 
    LOG = Logger.getLogger(Foo.class.getName());
...
}

I prefer to confine myself to three levels of logging: warnings, severe, and fine debugging.
LOG.severe("Something fatal just occurred.  Details follow: "+moreInfo);
LOG.warning("Something has me very worried.");'
LOG.fine("Only developers look at this.");

Severe warnings are expected to be fatal, so they save as much information as possible to reconstruct the problem. Normal warnings anticipate a serious problem, but they still think that recovery is possible.

Debug logging ("fine," "finer," and "finest") can be turned on by developers one package or class at a time, to discover unexpected behavior. It can also be useful for remote debugging at client sites.

Informative logging ("info") is much less useful in larger systems. It can too easily drown out useful information, unless culled very carefully by code audits. What seems informative in one package may just be background noise for another. If overused, it must be treated as the most general form of debug logging and suppressed in shipped code.

Of course, it should go without saying that no one should still be writing directly to System.out or System.err or calling Exception#printStackTrace(). You can log stack traces with Logger#log(Level.SEVERE,"Stack trace follows: ",exception);

You can also use logging for user interaction: [ Logging_for_error_dialogs.html ] .

Bill Harlan, March 2009


Return to parent directory.