Use custom handlers, filters, and formatters

In some cases you may wish to have your own custom log files. Adding custom handlers, filters, and formatters enables you to customize your logging environment beyond what can be achieved by configuration of the default WAS logging infrastructure.

The following example demonstrates how to add a new handler to process requests to the com.myCompany subtree of loggers (seeUnderstanding the logger hierarchy). The main method in this sample gives an example of how to use the newly configured logger.

import java.util.Vector;
import java.util.logging.Filter;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;

public class MyCustomLogging {

  public MyCustomLogging() {
    super();
  }

  public static void initializeLogging() {
    
    // Get the logger which we wish to attach a custom Handler to
    String defaultResourceBundleName = "com.myCompany.Messages";
    Logger logger = Logger.getLogger("com.myCompany", defaultResourceBundleName);
    
    // Set up a custom Handler (see MyCustomHandler example)
    Handler handler = new MyCustomHandler("MyOutputFile.log");
    
    // Set up a custom Filter (see MyCustomFilter example)
    Vector acceptableLevels = new Vector();
    acceptableLevels.add(Level.INFO);
    acceptableLevels.add(Level.SEVERE);
    Filter filter = new MyCustomFilter(acceptableLevels);
    
    // Set up a custom Formatter (see MyCustomFormatter example)
    Formatter formatter = new MyCustomFormatter();

    // Connect the filter and formatter to the handler
    handler.setFilter(filter);
    handler.setFormatter(formatter);
    
    // Connect the handler to the logger
    logger.addHandler(handler);
    
    // avoid sending events logged to com.myCompany showing up in WebSphere     // Application Server logs
    logger.setUseParentHandlers(false);
        
  }

  public static void main(String[] args) {
    initializeLogging();
    
    Logger logger = Logger.getLogger("com.myCompany");
    
    logger.info("This is a test INFO message");
    logger.warning("This is a test WARNING message");
    logger.logp(Level.SEVERE, "MyCustomLogging", "main", "This is a test SEVERE message");
  }
}

When the above program is executed, the output of the program is written to the MyOutputFile.log file. The content of the log is in the expected log file, as controlled by the custom handler, and is formatted as defined by the custom formatter. The warning message has been filtered out, as specified by the configuration of the custom filter. The output is as follows

C:\>type MyOutputFile.log
Sat Sep 04 11:21:19 EDT 2004 INFO This is a test INFO message
Sat Sep 04 11:21:19 EDT 2004 SEVERE This is a test SEVERE message