Using a java.util.logging ConsoleHandler

The following example uses a ConsoleHandler that logs to System.err. Our custom filter tells the logger only to log WARNING and FINE levels.

Main.java:

import java.util.logging.*;
import java.io.*;
 
public class Main
{
   public static void main(String argv[]) throws IOException {
      Logger logger = Logger.getLogger("main");
      logger.setUseParentHandlers(false);
      logger.setLevel(Level.ALL);
 
      ConsoleHandler ch = new ConsoleHandler();
      ch.setLevel(Level.ALL);
      ch.setFilter(new MyFilter());
      logger.addHandler(ch);
 
      logger.severe("log message #1");  
      logger.warning("log message #2");
      logger.info("log message #3");
      logger.config("log message #4");
      logger.fine("log message #5");
   }
}
 
class MyFilter implements Filter
{
   public boolean isLoggable(LogRecord lr) {
      if ((lr.getLevel() == Level.WARNING) ||
           (lr.getLevel() == Level.FINE))
         return true;
 
      return false;
   }
}

outputs:

Jan 20, 2002 4:46:14 AM Main main
WARNING: log message #2
Jan 20, 2002 4:46:15 AM Main main
FINE: log message #5