Using java.util.logging MemoryHandler

A MemoryHandler keeps track of a buffer of LogRecords in memory and will pass them on to another handler when a certain PushLevel is triggered. The following example creates a MemoryHandler that keeps track of maximum 5 LogRecords and writes to a ConsoleHandler when an error occurs that is equal or more “dangerous” than Level.WARNING.

Main.java:

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

public class Main
{
   public static void main(String argv[]) {
      Logger logger = Logger.getLogger("main");
      logger.setUseParentHandlers(false);
      logger.setLevel(Level.ALL);

      ConsoleHandler ch = new ConsoleHandler();
      ch.setLevel(Level.ALL);

      MemoryHandler mh = new MemoryHandler(ch, 5, Level.WARNING);
      mh.setLevel(Level.ALL);
      logger.addHandler(mh);

      logger.info  ("log message #1");
      logger.info  ("log message #2");
      logger.config("log message #3");
      logger.fine  ("log message #4");
      logger.config("log message #5");
      logger.info  ("log message #6");
      logger.config("log message #7");
      logger.fine  ("log message #8");
      logger.severe("log message #9");
   }
}

outputs:

Jan 20, 2002 4:21:35 PM Main main
CONFIG: log message #5
Jan 20, 2002 4:21:35 PM Main main
INFO: log message #6
Jan 20, 2002 4:21:35 PM Main main
CONFIG: log message #7
Jan 20, 2002 4:21:35 PM Main main
FINE: log message #8
Jan 20, 2002 4:21:35 PM Main main
SEVERE: log message #9