Home > Articles > Programming > Java

  • Print
  • + Share This
Like this article? We recommend

Adding a Custom Formatter

In this exercise, we'll add a custom HTML Formatter for our LogRecords. The Formatter class is shown below:

public class Formatter {
  public abstract String
   format(String s);
  public String
   formatMessage(String s);
  public String getHead(Handler h);
  public String getTail(Handler h);
}

To develop our own custom Formatter, we'll override the format method, using methods to access specific data from the LogRecord. The getHead() and getTail() methods are used for well-formed output formats such as XML. The following code describes a formatter class used to generate very simple HTML output:

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

// This custom formatter formats the logs into HTML format
// Each record is logged to a single line

class MyCustomFormatter extends Formatter {

  // This method is called for every log record

  public String format(LogRecord rec) {

   StringBuffer sb = new StringBuffer(1000);

   // give a red color to any messages with levels >= WARNING
   if (rec.getLevel().intValue() >= Level.WARNING.intValue()) {
        sb.append("<font color=\"red\">");
        sb.append(rec.getLevel());
        sb.append("</font>");
      } else {
        sb.append(rec.getLevel());
      }
      sb.append(' ');
      sb.append(formatMessage(rec));
      sb.append('\n');
      return sb.toString();
    }

    // This method is called when the handler is created

    public String getHead(Handler h) {
      return "<HTML><HEAD> My Custom Log from "+(new Date())+"</HEAD><BODY><H1>The logs</H1><PRE>\n";
    }

    // This method is called when the handler is closed

    public String getTail(Handler h) {
      return "</PRE></BODY></HTML>\n";
    }
  }

In this example, we'll modify the SimpleLogging.java file that we developed to replace the mylogging.properties file, to demonstrate that you always have the option to make calls to these classes programmatically.

package com.informit;

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


public class SimpleLogging {

public static void main(String[] args) {

// Get a logger

   Logger logger = Logger.getLogger("com.informit.SimpleLogging");

  try {
    // Create a file handler that uses the custom formatter
    FileHandler fh = new FileHandler("mycustom.html");
    fh.setFormatter(new MyCustomFormatter());
    logger.addHandler(fh);
  } catch (IOException e) {
  }

// Log a few messages at different severity levels
// There are seven different levels for logging
// You can choose a method specific to the logging level or
// the generic log method as shown

      logger.severe("Something really bad happened ");
      logger.warning("This is a warning");
      logger.log(Level.WARNING,"This is also a warning");
      logger.info("Just for your info");
      logger.config("A configuration message");
      logger.fine("A fine message");
      logger.finer("A finer message");
      logger.finest("A finest message");
      logger.log(Level.FINEST,"This is also a finest message");


     }
  }

On execution, the program produces the file mycustom.html (see Figure 1).

Figure 5Figure 1 The HTML output using the custom Formatter.

In this way you can extend the Formatter to output the log records in the format that you find to be most desirable.

  • + Share This
  • 🔖 Save To Your Account