Home > Articles > Programming > Java

  • Print
  • + Share This
Like this article? We recommend

Adding a Filter

The default configuration of the logging infrastructure doesn't use any filters. This is one of the least-used pieces of the logging framework. A Logger or a Handler can use the Filter to screen certain messages. The Filter interface is as follows:

public interface Filter {
  boolean isLoggable(LogRecord lr);

To add a Filter, simply create a class that implements the Filter interface, and return false for the isLoggable() method for any LogRecords that are to be eliminated.

import java.util.logging.*;

class MyCustomFilter
implements Filter 

// The method should return false when we do not wish
// to log the message

public boolean isLoggable(LogRecord rec) {
if (rec.getLevel().intValue() == Level.INFO.intValue())
       return false;
       return true;

Here we want to block any LogRecords with severity Level.INFO. We can add one more line to the SimpleLogging.java file, leaving the rest of the file unchanged, as shown below:

try {
   // Create a file handler that uses the custom formatter
   FileHandler fh = new FileHandler("mycustom.html");
   fh.setFormatter(new MyCustomFormatter());
   // Create the custom Filter
   logger.setFilter(new MyCustomFilter());
 } catch (IOException e) {

Running the SimpleLogging application produces a mycustom.html file with the messages with INFO log level eliminated. It's important to note that we could have used any of the methods of the LogRecord object to query any data element, and not just the Level.

  • + Share This
  • 🔖 Save To Your Account