Datasheet

The Formatter Class
The Formatter class is used to perform some custom processing on a log record. This formatting
might be localization, adding additional program information (such as adding the time and date to log
records), or any other processing needed. The
Formatter returns a string that is the processed log
record. The
Formatter class also has support for head and tail strings that come before and after all
log records. An example that will be implemented later in this section is a custom
Formatter that
writes log records to an HTML table. For this formatter, the head string would be the
<table> tag, and
the tail string is the
</table> tag. The methods defined in the Formatter class are listed in the follow-
ing table.
Method Description
abstract String format(LogRecord Performs specific formatting of the log record and
record) returns the formatted string.
String formatMessage(LogRecord The message string in the LogRecord is localized using
record) the record’s ResourceBundle, and formatted accord-
ing to
java.text style formatting (replacing strings
such as
{0}).
String getHead(Handler h) Returns the header string for a specified handler, which
can be null.
String getTail(Handler h) Returns the tail string for a specified handler, which
can be null.
Stock Formatters
The logging package comes already equipped with a couple of useful formatters. The SimpleFormatter
provides a basic implementation of a formatter. The XMLFormatter outputs log records in a predefined
XML format. These two stock formatters will cover a variety of basic logging scenarios, but if you need
behavior not supplied by either of these formatters, you can write your own.
SimpleFormatter
The SimpleFormatter does a minimal level of work to format log messages. The format method of the
SimpleFormatter returns a one- or two-line summary of the log record that is passed in. Logging a
simple log message, such as
test 1, using the SimpleFormatter will issue the following output:
Apr 18, 2004 12:18:25 PM LoggingTest main
INFO: test 1
The SimpleFormatter formats the message with the date, time, originating class name, originating
method name, and on the second line, the level of the log message and the log message itself.
XMLFormatter
The XMLFormatter formats the log records according to an XML DTD. You can use the XMLFormatter
with any character encoding, but it is suggested that it be used only with “UTF-8”. The getHead() and
52
Part I: Thinking Like a Java Developer
05_777106 ch01.qxp 11/28/06 10:43 PM Page 52