Example: Creating custom log handlers with java.util.logging
There may be occasions when you want to propagate log records to our own log handlers rather than participate in integrated logging.
To use a stand-alone log handler, set the useParentHandlers flag to false in the application.
The mechanism for creating a customer handler is the Handler class support that is provided by the IBM Developer Kit, Java Technology Edition. If not familiar with handlers, as implemented by the Developer Kit, we can get more information from various texts, or by reading the API documentation for the java.util.logging API.
The following sample shows a custom handler:
import java.io.FileOutputStream; import java.io.PrintWriter; import java.util.logging.Handler; import java.util.logging.LogRecord; /** * MyCustomHandler outputs contents to a specified file */ public class MyCustomHandler extends Handler { FileOutputStream fileOutputStream; PrintWriter printWriter; public MyCustomHandler(String filename) { super(); // check input parameter if (filename == null || filename == "") filename = "mylogfile.txt"; try { // initialize the file fileOutputStream = new FileOutputStream(filename); printWriter = new PrintWriter(fileOutputStream); setFormatter(new SimpleFormatter()); } catch (Exception e) { // implement exception handling... } } /* (non-API documentation) * @see java.util.logging.Handler#publish(java.util.logging.LogRecord) */ public void publish(LogRecord record) { // ensure that this log record should be logged by this Handler if (!isLoggable(record)) return; // Output the formatted data to the file printWriter.println(getFormatter().format(record)); } /* (non-API documentation) * @see java.util.logging.Handler#flush() */ public void flush() { printWriter.flush(); } /* (non-API documentation) * @see java.util.logging.Handler#close() */ public void close() throws SecurityException { printWriter.close(); } }
Related tasks
Set the logger hierarchy
Create log resource bundles and message files
Use a logger
Related
Example: Creating custom filters with java.util.logging
Example: Creating custom formatters with java.util.logging
Example: Adding custom handlers, filters, and formatters