In this example we demonstrate the use of Logger
‘s MemoryHandler
to log only when some conditions happen in our application, for example when a Level.SEVERE
message is logged.
We create an instance of MemoryHandler
that will delegate the log to FileHandler
class, and it logs the last 100 record until a Level.SEVERE
message is logged.
package org.kodejava.util.logging;
import java.util.logging.Logger;
import java.util.logging.FileHandler;
import java.util.logging.MemoryHandler;
import java.util.logging.Level;
public class MemoryHandlerDemo {
public static void main(String[] args) {
MemoryHandlerDemo demo = new MemoryHandlerDemo();
try {
demo.testMethod();
} catch (Exception e) {
e.printStackTrace();
}
}
public void testMethod() throws Exception {
Logger logger = Logger.getLogger(MemoryHandlerDemo.class.getName());
FileHandler fileHandler = new FileHandler("myapp.log");
// Create a MemoryHandler that will dump the log messages for the
// latest 100 records when a Level.SEVERE log is logged to by the
// Logger class.
MemoryHandler memoryHandler = new MemoryHandler(fileHandler, 100, Level.SEVERE);
logger.addHandler(memoryHandler);
// Write some messages to the log
logger.info("Information message");
logger.warning("Warning message");
// This causes the log messages dump to the file log.
logger.severe("Severe message");
}
}
To check if the message is logged you can open the myapp.log
file created by this small program.
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024