Datasheet
Creating Your Own Formatter
It isn’t too difficult to develop a custom Formatter. As an example, here’s an implementation of the
HTMLTableFormatter that was mentioned previously. The HTML code that is output looks like this:
<table border>
<tr><th>Time</th><th>Log Message</th></tr>
<tr><td>...</td><td>...</td></tr>
<tr><td>...</td><td>...</td></tr>
</table>
Each log record starts with <tr> and ends with </tr> because there is only one log record per table row.
The
<table> tag and the first row of the table make up the head string. The </table> tag makes up the
tail of the collection of log records. The custom formatter only needs an implementation of the
getHead(),
getTail(), and format(LogRecord record) methods:
import java.util.logging.*;
class HTMLTableFormatter extends java.util.logging.Formatter {
public String format(LogRecord record)
{
return(“ <tr><td>” +
record.getMillis() +
“</td><td>” +
record.getMessage() +
“</td></tr>\n”);
}
public String getHead(Handler h)
{
return(“<table border>\n “ +
“<tr><th>Time</th><th>Log Message</th></tr>\n”);
}
public String getTail(Handler h)
{
return(“</table>\n”);
}
}
The Filter Interface
A filter is used to provide additional criteria to decide whether to discard or keep a log record. Each log-
ger and each handler can have a filter defined. The
Filter interface defines a single method:
boolean isLoggable(LogRecord record)
The isLoggable method returns true if the log message should be published and false if it should be
discarded.
55
Chapter 1: Key Java Language Features and Libraries
05_777106 ch01.qxp 11/28/06 10:43 PM Page 55