Datasheet

Because the log messages are then sent to the parent logger, the messages are also output to System.err
using the SimpleFormatter. The following is output:
Feb 11, 2004 2:09:55 PM LoggingExample1 main
INFO: test 1
Feb 11, 2004 2:09:56 PM LoggingExample1 main
INFO: test 2
Here’s a more detailed example that uses the already developed HTMLTableFormatter. Two loggers are
defined in a parent-child relationship,
ParentLogger and ChildLogger. The parent logger will use the
XMLFormatter to output to a text file, and the child logger will output using the HTMLTableFormatter
to a different file. By default, the root logger will execute and the log messages will go to the console
using the
SimpleFormatter. The HTMLTableFormatter is extended to an HTMLFormatter to generate
a full HTML file (instead of just the table tags):
import java.util.logging.*;
import java.util.*;
class HTMLFormatter extends java.util.logging.Formatter {
public String format(LogRecord record)
{
return(“ <tr><td>” +
(new Date(record.getMillis())).toString() +
“</td>” +
“<td>” +
record.getMessage() +
“</td></tr>\n”);
}
public String getHead(Handler h)
{
return(“<html>\n <body>\n” +
“ <table border>\n “ +
“<tr><th>Time</th><th>Log Message</th></tr>\n”);
}
public String getTail(Handler h)
{
return(“ </table>\n </body>\n</html>”);
}
}
public class LoggingExample2 {
public static void main(String args[])
{
try {
LogManager lm = LogManager.getLogManager();
Logger parentLogger, childLogger;
FileHandler xml_handler = new FileHandler(“log_output.xml”);
FileHandler html_handler = new FileHandler(“log_output.html”);
parentLogger = Logger.getLogger(“ParentLogger”);
childLogger = Logger.getLogger(“ParentLogger.ChildLogger”);
lm.addLogger(parentLogger);
58
Part I: Thinking Like a Java Developer
05_777106 ch01.qxp 11/28/06 10:43 PM Page 58