Java Reference
In-Depth Information
Figure 16.10
Output of the LoggingDemo program.
An Example of Logging
Let's look at an example that puts together these various logging classes so you
can see how they are used. The following LoggingDemo program logs mes-
sages to a file named messages.log. The XMLFormatter is used to demonstrate
how messages look in XML.
import java.util.logging.*;
import java.io.IOException;
public class LoggingDemo
{
public static void main(String [] args)
{
Logger logger = Logger.getLogger(“my.log”);
Handler handler = null;
try
{
handler = new FileHandler(“messages.log”);
}catch(IOException e)
{
System.out.println(“Using the console handler”);
handler = new ConsoleHandler();
}
logger.addHandler(handler);
handler.setFormatter(new XMLFormatter());
logger.info(“Our first logging message”);
logger.severe(“Something terrible happened”);
}
}
Figure 16.10 shows the console output from running the LoggingDemo.
Notice that even though the output was sent to a file, the INFO and SEVERE
logs also display a message at the console output.
The file messages.log contains the output of the two logged messages in
XML format. The XML tags used are the standard for log messages, and using
XML allows you to write applications that display the logged messages in
many different ways. Here is what the messages.log file looks like:
Search WWH ::




Custom Search