logging
Set filter on Logger handler
This is an example of how to set a filter on a Logger’s Handler. The Filter is used to provide control over what is logged, beyond the control that the levels provide. Each Logger and each Handler can have a filter associated with it. The Logger or Handler will call the isLoggable(LogRecord record)
method to check if a given LogRecord should be published. Setting filter on Logger handler implies that you should:
- Create a new FileHandler that will append to a specific file.
- Create a new Filter that will override the
isLoggable(LogRecord record)
method of the Handler, in order to check which messages will be published. - Set the Filter to control the handler’s output, with the
setFilter(Filter newFilter)
API method of the Handler. - Create a new Logger instance and add the handler to the logger, with the
addHandler(Handler handler)
API method of the Logger. - Invoke the
setLevel(Level newLevel)
API method of the Logger to set a Level to the logger. - Log messages using one of the logger’s methods. In the example the
info(String msg)
method is used to log messages in levelINFO
. Since the Logger’s Level is set toFINEST
the messages should be all forwarded to the Handler, but since the Filter is used only messages that start with IMPORTANT will be writen in the log file by the FileHandler.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; import java.util.logging.FileHandler; import java.util.logging.Filter; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; public class SetFilterOnLoggerHandler { public static void main(String[] args) throws Exception { boolean append = false; FileHandler handler = new FileHandler("default.log", append); handler.setFilter(new Filter() { @Override public boolean isLoggable(LogRecord record) { return record.getMessage().startsWith("IMPORTANT"); } }); Logger logger = Logger.getLogger("com.javacodegeeks.snippets.core"); logger.addHandler(handler); logger.setLevel(Level.FINEST); logger.info("info message"); logger.info("IMPORTANT info message"); } }
Output:
Nov 19, 2011 3:56:13 PM com.javacodegeeks.snippets.core.SetFilterOnLoggerHandler main
INFO: info message
Nov 19, 2011 3:56:13 PM com.javacodegeeks.snippets.core.SetFilterOnLoggerHandler main
INFO: IMPORTANT info message
default.log
<?xml version="1.0" encoding="windows-1252" standalone="no"?> <!DOCTYPE log SYSTEM "logger.dtd"> <log> <record> <date>2011-11-19T15:56:13</date> <millis>1321710973344</millis> <sequence>1</sequence> <logger>com.javacodegeeks.snippets.core</logger> <level>INFO</level> <class>com.javacodegeeks.snippets.core.SetFilterOnLoggerHandler</class> <method>main</method> <thread>10</thread> <message>IMPORTANT info message</message> </record> </log>
This was an example of how to set a filter on a Logger’s Handler in Java.