Wednesday, February 01, 2006

JDK 1.4 Logging

The JDK defines 5 handlers:

* StreamHandler : sends messages to an OutputStream
* ConsoleHandler: sends messages to System.err
* FileHandler: sends messages to a file
* SocketHandler: sends messages to a TCP port
* MemoryHandler: buffers messages in memory

Sun has defined two formatters:

* SimpleFormatter: defines a simple message format containing among other things a timestamp
* XMLFormatter: a message in XML format

A logger with a ConsoleHandler with low priority level:

Logger logger1 = Logger.getLogger("abc.def");
ConsoleHandler c1 = new ConsoleHandler();

A logger with a FileHandler using a home made formatter:

Logger logger2 = Logger.getLogger("abc.def.ghi");
FileHandler f2 = new FileHandler("%h/mylog.txt", 10000, 2, false);
f2.setFormatter(new MyFormatter());


Every handler must have a formatter defined, and the API has pre-defined a SimpleFormatter and an XMLFormatter which both extend the abstract class Formatter. You may define your own formatter if you like, and it's actually quite simple. You only have to implement the format method. This method receives an instance of the LogRecord class which contains several properties. format returns a string with the data that should be logged. In the next example I've made a formatter that returns the most important properties from the LogRecord:

import java.util.*;
import java.util.logging.*;

public class MyFormatter extends Formatter {
public String format(LogRecord record) {
"LogRecord info:\n" +
"Level: " + record.getLevel() + '\n' +
"LoggerName: " + record.getLoggerName() + '\n' +
"Message: " + record.getMessage() + '\n' +
" " + record.getMillis() + '\n' +
"Sequence Number: " + record.getSequenceNumber() + '\n' +
"SourceClassName: " + record.getSourceClassName() + '\n' +
"SourceMethodName: " + record.getSourceMethodName() + '\n' +
"ThreadID: " + record.getThreadID() + '\n';

No comments: