Create a custom log handler

There may be occasions when you only want to propagate log records to your own log handlers, rather than participate in integrated logging. To use a stand alone log handler, set the "useParentHandlers" flag to false in your application.

The mechanism for creating a customer handler is the Handler class support provided by the IBM Developer Kit, Java Technology Edition. If you are not familiar with handlers as implemented by the Developer's Kit, one can get more information from various texts, or by reading the Javadoc for java.util.logging.

The following is a sample of a custom handler

import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.logging.Handler;
import java.util.logging.LogRecord;

/**
 * MyCustomHandler outputs contents to a specified file
 */
public class MyCustomHandler extends Handler {

  FileOutputStream fileOutputStream;
  PrintWriter printWriter;

  public MyCustomHandler(String filename) {
    super();

    // check input parameter
    if (filename == null)
      filename = "mylogfile.txt";
    
    try {
      // initialize the file 
      fileOutputStream = new FileOutputStream(filename);
      printWriter = new PrintWriter(fileOutputStream);
    }
    catch (Exception e) {
      // implement exception handling...
    }
  }

  /* (non-Javadoc)
   * @see java.util.logging.Handler#publish(java.util.logging.LogRecord)
   */
  public void publish(LogRecord record) {
    // ensure that this LogRecord should be logged by this Handler
    if (!isLoggable(record))
      return;
    
    // Output the formatted data to the file
    printWriter.println(getFormatter().format(record));
  }

  /* (non-Javadoc)
   * @see java.util.logging.Handler#flush()
   */
  public void flush() {
    printWriter.flush();
  }

  /* (non-Javadoc)
   * @see java.util.logging.Handler#close()
   */
  public void close() throws SecurityException {
    printWriter.close();
  }
}

 



 

 

IBM is a trademark of the IBM Corporation in the United States, other countries, or both.