Java by API/java.util.logging/Handler
Handler: setFormatter(Formatter newFormatter)
import java.io.IOException;
import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Logger;
import java.util.logging.XMLFormatter;
public class MainClass {
public static void main(String args[]) {
Logger logger = Logger.getLogger("my.log");
Handler handler = null;
try {
handler = new FileHandler("messages.log");
} catch (IOException e) {
System.out.println("Could not create file. Using the console handler");
handler = new ConsoleHandler();
}
logger.addHandler(handler);
handler.setFormatter(new XMLFormatter());
logger.info("Our first logging message");
logger.severe("Something terrible happened");
}
}
implements Handler
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
public class Main {
private static Logger logger = Logger.getLogger("CustomHandler");
private static List<String> strHolder = new ArrayList<String>();
public static void main(String[] args) {
logger.addHandler(new Handler() {
public void publish(LogRecord logRecord) {
strHolder.add(logRecord.getLevel() + ":");
strHolder.add(logRecord.getSourceClassName() + ":");
strHolder.add(logRecord.getSourceMethodName() + ":");
strHolder.add("<" + logRecord.getMessage() + ">");
strHolder.add("\n");
}
public void flush() {
}
public void close() {
}
});
logger.warning("Logging Warning");
logger.info("Logging Info");
System.out.print(strHolder);
}
}