Writing Log Records Only After a Condition Occurs with MemoryHandler - Java Java Virtual Machine

Java examples for Java Virtual Machine:Logger

Description

Writing Log Records Only After a Condition Occurs with MemoryHandler

Demo Code


import java.awt.Graphics;
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.MemoryHandler;

public class Main {
  public void m() {
    try {//from  ww w  .  java  2  s.c  o  m
      FileHandler fhandler = new FileHandler("my.log");
      int numRec = 100;
      MemoryHandler mhandler = new MemoryHandler(fhandler, numRec, Level.OFF) {
        public synchronized void publish(LogRecord record) {
          // Log it before checking the condition
          super.publish(record);

          boolean condition = false;
          if (condition) {
            // Condition occurred so dump buffered records
            push();
          }
        }
      };

      // Add to the desired logger
      Logger logger = Logger.getLogger("com.mycompany");
      logger.addHandler(mhandler);
    } catch (IOException e) {
    }
  }
}

Related Tutorials