Use Logger MemoryHandler class

In this example we shall show you how to use the Logger MemoryHandler class. The MemoryHandler is a Handler that buffers requests in a circular buffer in memory. To use the MemoryHandler of a logger one should perform the following steps:

Note that only messages for the specific level will be dumbed to the file log, as described in the code snippet below.

package com.javacodegeeks.snippets.core;
import java.util.logging.Logger;
import java.util.logging.FileHandler;
import java.util.logging.MemoryHandler;
import java.util.logging.Level;
 
public class MemoryHandlerExample {
	
    public static void main(String[] args) {
    	
    	MemoryHandlerExample example = new MemoryHandlerExample();
  try {
example.testMethod();
  } catch (Exception e) {
e.printStackTrace();
  }
    }
 
    public void testMethod() throws Exception {
  Logger logger = Logger.getLogger(MemoryHandlerExample.class.getName());
  FileHandler fileHandler = new FileHandler("myapp.log");
 
  // Create a MemoryHandler that will dump the log messages for the
  // latest 10 records when a Level.SEVERE log is logged 
  MemoryHandler memoryHandler = new MemoryHandler(fileHandler, 10, Level.SEVERE);
  logger.addHandler(memoryHandler);
 
  // Write messages to the log
  logger.info("Info message");
  logger.warning("Warning message");
   
  //
  // This causes the log messages dump to the file log.
  //
  logger.severe("Severe message");
    }
}

Output:

Αυγ 12, 2012 1:39:23 ΜΜ com.javacodegeeks.snippets.core.MemoryHandlerExample testMethod
INFO: Info message
Αυγ 12, 2012 1:39:23 ΜΜ com.javacodegeeks.snippets.core.MemoryHandlerExample testMethod
WARNING: Warning message
Αυγ 12, 2012 1:39:23 ΜΜ com.javacodegeeks.snippets.core.MemoryHandlerExample testMethod
SEVERE: Severe message

 
This was an example of how to use Logger MemoryHandler class in Java.

Exit mobile version