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:
- Create a Logger instance, with the
getLogger(String name)
API method of the Logger. - Initialize a FileHandler to write to the given String filename.
- Create a MemoryHandler that will dump to the FileHandler a specific number of log records when a log is logged for a specific level (in the example 10 records are dumbed to the FileHandler when a Level.SEVERE log is logged).
- Add the memoryHandler to the logger so as to receive logging messages, with
addHandler(Handler handler)
API method. - Write messages to the log.
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.