The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.util.logging  [20 examples] > Formatters  [2 examples]

e400. 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 e399 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>

 Related Examples
e399. Setting the Formatter of a Logger Handler

See also: Configuration    File Size    Levels   


© 2002 Addison-Wesley.