How do I set a filter on a logger handler?

This example give you an example on how to set the Filter of a logger handler. In the code below we implement the Filter on the FileHandler to log only a Level.SEVERE message. Other log level will not be recorded to the file.

package org.kodejava.util.logging;

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

public class LoggerFilter {
    public static void main(String[] args) {
        Logger logger = Logger.getLogger(LoggerFilter.class.getName());

        FileHandler handler = null;
        try {
            handler = new FileHandler("myapp.log");
            // The message will be recorded to the file When the 
            // LogRecord level is equals to Level.SEVERE
            handler.setFilter(record -> record.getLevel().equals(Level.SEVERE));
        } catch (IOException e) {
            logger.log(Level.SEVERE, "Fail to create logger handler", e);
        }

        logger.addHandler(handler);

        logger.info("Information message");
        logger.warning("Warning message");
        logger.severe("Severe message");
    }
}
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.