- Understanding the Structure of the Logging API
- Creating a Handler Class
- Constructing your Publish Method
- Conclusions
Constructing your Publish Method
What is done by your publish method is determined by what sort of a handler you are creating. There are many different tasks that handlers can be used for. Some examples include the following:
Log data to a JDBC data source
Log data to a remote socket
Page a user when a specific error occurs
Send a status email with a specific error occurs
I will now show you an example of exactly how a handler class would be constructed. Listing 1 shows the structure that your handler class would have.
Listing 1[em]A Simple Log Handler
import java.util.logging.*; /** * JDBC Logging Article * * This is a reusable class that implements * a JDK1.4 log handler. * * ©author Jeff Heaton (http://www.jeffheaton.com) * ©version 1.0 * ©since November 2002 */ public class EMailLogHandler extends Handler { /** * Overridden method used to capture log entries and put them * into a JDBC database. * * @param record The log record to be stored. */ public void publish(LogRecord record) { // first see if this entry should be filtered out // the filter should keep anything if ( getFilter()!=null ) { if ( !getFilter().isLoggable(record) ) return; } // send an email indicating that problem has occurred } /** * Called to close this log handler. */ public void close() { // not used } /** * Called to flush any cached data that * this log handler may contain. */ public void flush() { // not used } }
This handler is designed to send an email message for each log entry that is received. The code is not provided to actually send the email or page a user. You will need to implement this functionality in a way that is supported by your email or paging systems.
Notice that no filtering is done inside of the handler. Any LogRecord that is sent to the handler will be logged. A filter will prevent the user from getting an email or page for each log entry that is made.