Creating a Custom Formatter for a Logger Handler

A logger's handler uses a formatter to write a log record out to the log file. The java.util.logging package provides two formatters; see Setting the Formatter of a Logger Handler for more information. However, the logging package allows you to create custom formatters.

This example creates a custom formatter that prints one line for each log record and surrounds the log data with HTML tags.

// This custom formatter formats parts of a log record to a single line class MyHtmlFormatter extends Formatter { // This method is called for every log records public String format(LogRecord rec) { StringBuffer buf = new StringBuffer(1000); // Bold any levels >= WARNING if (rec.getLevel().intValue() >= Level.WARNING.intValue()) { buf.append("<b>"); buf.append(rec.getLevel()); buf.append("</b>"); } else { buf.append(rec.getLevel()); } buf.append(' '); buf.append(rec.getMillis()); buf.append(' '); buf.append(formatMessage(rec)); buf.append('\n'); return buf.toString(); } // This method is called just after the handler using this // formatter is created public String getHead(Handler h) { return "<HTML><HEAD>"+(new Date())+"</HEAD><BODY><PRE>\n"; } // This method is called just after the handler using this // formatter is closed public String getTail(Handler h) { return "</PRE></BODY></HTML>\n"; } }
Here's some code to use the custom formatter:
// Get the logger Logger logger = Logger.getLogger("com.mycompany"); try { // Create a file handler that uses the custom formatter FileHandler fh = new FileHandler("mylog.html"); fh.setFormatter(new MyHtmlFormatter()); logger.addHandler(fh); } catch (IOException e) { } // Log some messages logger.setLevel(Level.ALL); logger.severe("my severe message"); logger.info("my info message"); logger.entering(this.getClass().getName(), "myMethod", new Object[]{"para1", "para2"});
Here's the output from the example code above:
<HTML><HEAD>Fri Jan 11 13:32:57 PST 2002</HEAD><BODY><PRE> <b>SEVERE</b> 1010784777240 my severe message INFO 1010784777390 my info message FINER 1010784777400 ENTRY para1 para2 </PRE></BODY></HTML>

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.