+

Search Tips   |   Advanced Search

 

Example: Creating custom log handlers with java.util.logging

 

There may be occasions when you 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 that is provided by the IBM Developer Kit, Java Technology Edition. If you are not familiar with handlers, as implemented by the Developer Kit, you can get more information from various texts, or by reading the API documentation for the java.util.logging API. The following sample shows 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-API documentation)
   * @see java.util.logging.Handler#publish(java.util.logging.LogRecord)
   */
  public void publish(LogRecord record) {
    // ensure that this log record should be logged by this Handler
    if (!isLoggable(record))
      return;
    
    // Output the formatted data to the file
    printWriter.println(getFormatter().format(record));
  }

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

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



 

Related tasks


Configure the logger hierarchy
Creating log resource bundles and message files
Use a logger

 

Related Reference


Example: Creating custom filters with java.util.logging
Example: Creating custom formatters with java.util.logging
Example: Adding custom handlers, filters, and formatters

 

Reference topic