How to set up a logging filter in Java
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.
The setFilter() method
The 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.
Syntax
logger.setFilter(Filter customFilter);
boolean isLoggable(LogRecord record);
Parameters
-
customFilter: This is the custom filter that needs to be set on the logger. -
record:This is the log record.
Return value
The isLoggable() method returns true if the log record has to be published. Otherwise, it returns false.
Code example
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
INFOkeyword withWARNINGin line 17 to display thewarninglevel log.
Code explanation
- Lines 1-3: Relevant classes and packages are imported.
- Line 8: A logger is created with the name of the
Mainclass. - Line 9: We set the filter of the logger to our custom filter via the
setFilter()method. An instance ofCustomFilterclass is passed as the parameter. - Line 10: An
INFOlevel log message is sent to the logger. - Line 11: A
WARNINGlevel log message is sent to the logger. - Lines 15-19: A custom filter by the name
CustomFilteris defined here which implements theFilterinterface. TheisLoggable()method is overridden here that only returnstrueforINFOlevel log messages andfalsefor all other level log messages.
Note: The key observation here is that only the
INFOlevel log gets printed to the console while theWARNINGlevel log is ignored.
Free Resources