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");
logger1.setLevel(Level.FINEST);
ConsoleHandler c1 = new ConsoleHandler();
c1.setLevel(Level.FINEST);
logger1.addHandler(c1);
A logger with a FileHandler using a home made formatter:
Logger logger2 = Logger.getLogger("abc.def.ghi");
logger2.setLevel(Level.CONFIG);
FileHandler f2 = new FileHandler("%h/mylog.txt", 10000, 2, false);
f2.setFormatter(new MyFormatter());
f2.setLevel(Level.CONFIG);
logger2.addHandler(f2);
Formatters
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) {
return
"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:
Post a Comment