Open In App

Logger setFilter() method in Java with Examples

Improve
Improve
Like Article
Like
Save
Share
Report

setFilter() method of a Logger class is used to set a filter to control output on this Logger. The filter is passed as a parameter. A Filter is useful to filter out log messages. It can be said that the filter decides the message gets to be logged or not. Filters are represented by the Java interface java.util.logging.Filter. After passing the initial “level” check, the Logger will call this Filter to check if a log record should really be published.

Syntax:

public void setFilter(Filter newFilter)
               throws SecurityException

Parameters: This method accepts one parameter newFilter which represents a filter object.

Return value: This method returns nothing.

Exception: This method throws SecurityException if a security manager exists, this logger is not anonymous, and the caller does not have LoggingPermission(“control”).

Below programs illustrate the setFilter() method:
Program 1:




// Java program to demonstrate
// Logger.setFilter() method
  
import java.util.logging.*;
import java.io.IOException;
  
public class GFG {
  
    public static void main(String[] args)
        throws SecurityException, IOException
    {
  
        // Create a logger
        Logger logger
            = Logger.getLogger(GFG.class.getName());
  
        // set a new filter
        logger.setFilter(new MyFilter());
  
        // check filter is null or not by printing
        System.out.println("Filter = "
                           + logger.getFilter());
    }
}
class MyFilter implements Filter {
    public boolean isLoggable(LogRecord record)
    {
        return false;
    }
}


Output:
The output printed on console of Eclipse is shown below-

Program 2:




// Java program to demonstrate
// Logger.setFilter() method
  
import java.util.logging.*;
import java.io.IOException;
  
public class GFG {
  
    public static void main(String[] args)
        throws SecurityException, IOException
    {
  
        // Create a logger
        Logger logger
            = Logger.getLogger(
                GFG.class.getName());
  
        // Set a new filter
        logger.setFilter(new Filter() {
            @Override
            public boolean isLoggable(LogRecord record)
            {
                return true;
            }
        });
  
        // Check filter is null
        // or not by printing
        System.out.println("Filter = "
                           + logger.getFilter());
    }
}


Output:
The output printed on console output is shown below-

References: https://docs.oracle.com/javase/10/docs/api/java/util/logging/Logger.html#setFilter(java.util.logging.Filter)



Last Updated : 26 Mar, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads