A filter as the name suggests, is used to filter out the log messages. Every log message is passed through the filter, and the filter decides which messages get logged. Hence, it is important to configure filters for loggers in Java.
setFilter()
methodThe setFilter()
method is used to set a custom logging filter. A custom logging filter can be defined by implementing the java.util.logging.Filter
interface. The interface consists of one method called isLoggable()
where every log record/message is passed to this method. The method returns a boolean value that indicates whether the log record should be published.
logger.setFilter(Filter customFilter);
boolean isLoggable(LogRecord record);
customFilter
: This is the custom filter that needs to be set on the logger.
record
:This is the log record.
The isLoggable()
method returns true
if the log record has to be published. Otherwise, it returns false
.
Let’s look at the code below:
import java.util.logging.Filter;import java.util.logging.LogRecord;import java.util.logging.Logger;public class Main {public static void main(String[] args) {Logger logger = Logger.getLogger(Main.class.getName());logger.setFilter(new CustomFilter());logger.info("This is an info message");logger.warning("This is a warning message");}}class CustomFilter implements Filter {public boolean isLoggable(LogRecord logRecord) {return logRecord.getLevel().getName().equals("INFO");}}
Note: Replace the
INFO
keyword withWARNING
in line 17 to display thewarning
level log.
Main
class.setFilter()
method. An instance of CustomFilter
class is passed as the parameter.INFO
level log message is sent to the logger.WARNING
level log message is sent to the logger.CustomFilter
is defined here which implements the Filter
interface. The isLoggable()
method is overridden here that only returns true
for INFO
level log messages and false
for all other level log messages.Note: The key observation here is that only the
INFO
level log gets printed to the console while theWARNING
level log is ignored.
Free Resources