MyHtmlFormatter.java Source code

Java tutorial

Introduction

Here is the source code for MyHtmlFormatter.java

Source

import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

class MyHtmlFormatter extends Formatter {
    public String format(LogRecord rec) {
        StringBuffer buf = new StringBuffer(1000);
        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();
    }

    public String getHead(Handler h) {
        return "<HTML><HEAD>" + (new Date()) + "</HEAD><BODY><PRE>\n";
    }

    public String getTail(Handler h) {
        return "</PRE></BODY></HTML>\n";
    }
}

public class Main {
    public static void main(String[] argv) throws Exception {
        Logger logger = Logger.getLogger("com.mycompany");
        FileHandler fh = new FileHandler("mylog.html");
        fh.setFormatter(new MyHtmlFormatter());
        logger.addHandler(fh);

        logger.setLevel(Level.ALL);
        logger.severe("my severe message");
        logger.info("my info message");
        logger.entering("Main class", "myMethod", new Object[] { "para1", "para2" });
    }
}