Java Reference
In-Depth Information
The logger class has several utility methods for logging information (
Logger.info(<msg>)
),
warning (
Logger.warning(<msg>)
), and severe (
Logger.severe(<msg>)
) messages, allowing you
to log simple messages, for example:
myLogger.severe("Sending message to standard error");
If you have been putting these commands into simple test applications, you may be won-
dering what the fuss is about—after all, so far we have not done anything that we cannot do
with a
System.out.println(<msg>)
statement. But consider that you could turn off all logging
to your
entire
application with one statement near the start of your application, such as
myLogger.setLevel(Level.OFF);
That is, all your classes could be logging messages, at different levels, and that one line
could turn them all off—no need to go hunting for all those
System.out.println(<msg>)
statements.
You may want to execute a block of logging code only if you know that it is actually going
to be logged. In such a case, you can make a call to the
isLoggable(<level>)
method first to
determine whether you should call your (potentially performance-reducing) logging code.
One benefit we mentioned earlier was that we could log messages to a file—this is done
through a
Handler
object. We can add a simple file handler to our logger with one simple
command:
import java.util.logging.*;
import java.io.IOException;
public class TestLogging {
public static void main(String[] args) throws IOException {
Logger myLogger = Logger.getLogger("Test");
myLogger.addHandler(new FileHandler("temp.log"));
myLogger.severe("My program did something bad");
}
}
■
Note
The
FileHandler
class can handle storing logs in common locations regardless of operating sys-
tem, and can handle the usual issues such as rotating log files. Refer to the API for
FileHandler
to see how
such options can be utilized.
Running this example produces the following log message:
C:\TEMP> java TestLogging
11/12/2004 19:22:40 TestLogging main
SEVERE: My program did something bad
■
Note
Your time and date will obviously differ.