Log HTML formatter : Log Formatter « Log « Java Tutorial






import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.XMLFormatter;

class HTMLFormatter extends java.util.logging.Formatter {
  public String format(LogRecord record) {
    return ("<tr><td>" + (new Date(record.getMillis())).toString() + "</td><td>"
        + record.getMessage() + "</td></tr>\n");
  }

  public String getHead(Handler h) {
    return ("<html>\n  <body>\n" + "<Table border>\n<tr><td>Time</td><td>Log Message</td></tr>\n");
  }

  public String getTail(Handler h) {
    return ("</table>\n</body>\n</html>");
  }
}

public class LoggingHTMLFormatter {
  public static void main(String args[]) throws Exception {
      LogManager lm = LogManager.getLogManager();
      Logger parentLogger, childLogger;
      FileHandler xml_handler = new FileHandler("log_output.xml");
      FileHandler html_handler = new FileHandler("log_output.html");
      parentLogger = Logger.getLogger("ParentLogger");
      childLogger = Logger.getLogger("ParentLogger.ChildLogger");

      lm.addLogger(parentLogger);

      lm.addLogger(childLogger);

      parentLogger.setLevel(Level.WARNING);
      childLogger.setLevel(Level.ALL);
      xml_handler.setFormatter(new XMLFormatter());
      html_handler.setFormatter(new HTMLFormatter());

      parentLogger.addHandler(xml_handler);
      childLogger.addHandler(html_handler);

      childLogger.log(Level.FINE, "This is a fine log message");
      childLogger.log(Level.SEVERE, "This is a severe log message");
      xml_handler.close();
      html_handler.close();
  }
}








35.4.Log Formatter
35.4.1.Set log Formatter
35.4.2.Create custom formatter
35.4.3.Define your own Custom Formatter
35.4.4.Log HTML formatter
35.4.5.Logger with XMLFormatter and FileHandler
35.4.6.XMLFormatter based Logging
35.4.7.Creating a Custom Formatter for a Logger Handler
35.4.8.Setting the Formatter of a Logger Handler