package at.oefai.aaa;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.MessageFormat;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;
import java.security.AccessController;
import java.security.PrivilegedAction;

/**
 * Gives a simple (mostly) one line log message including date and time.
 * @author Stefan Rank
 */
public class SimplestFormatter extends Formatter {
    private Date date = new Date();
    //private static final String FORMAT = "{0,date} {0,time,HH:mm:ss.SSS}";
    private static final String FORMAT = "{0,time,HH:mm:ss.SSS}";
    private static final MessageFormat FORMATTER = new MessageFormat(FORMAT);
    private Object[] args = new Object[1];
    // Line separator string.  This is the value of the line.separator
    // property at the moment that the SimpleFormatter was created.
    private String lineSeparator = AccessController.doPrivileged(
            new PrivilegedAction<String>() {
                public String run() {
                    return System.getProperty("line.separator");
                }
            });
    // the privileged action used should be the same as
    //new sun.security.action.GetPropertyAction("line.separator")
    // but with template (so the compiler knows it returns String)

    /**
     * Format the given LogRecord.
     * @param record the log record to be formatted.
     * @return a formatted log record
     */
    public synchronized String format(final LogRecord record) {
        StringBuffer sb = new StringBuffer();
        // Minimize memory allocations here.
        this.date.setTime(record.getMillis());
        this.args[0] = this.date;
        StringBuffer text = new StringBuffer();
        FORMATTER.format(this.args, text, null);
        sb.append(text);
        sb.append(":");
        sb.append(record.getLevel().getLocalizedName());
        sb.append(":\t");
        StringBuffer lname = new StringBuffer("            ");
        String loggername = record.getLoggerName();
        if (loggername.length() > 0) {
            lname.replace(0, loggername.length() - 1, loggername);
        }
        sb.append(lname);
        if (record.getSourceClassName() != null) {
            sb.append(" ");
            sb.append(record.getSourceClassName());
        }
        if (record.getSourceMethodName() != null) {
            sb.append(" ");
            sb.append(record.getSourceMethodName());
        }
        sb.append("\t");
        String message = formatMessage(record);
        sb.append(message);
        sb.append(this.lineSeparator);
        if (record.getThrown() != null) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            record.getThrown().printStackTrace(pw);
            pw.close();
            sb.append(sw.toString());
        }
        return sb.toString();
    }

}
