!!Opensource Java Code

Logging much? Make your logs easier to parse or load into MySQL by using CSV output.

[{SyntaxHighlighter code='java'

/*
 * Copyright Scott Douglass, 2012.
 *
 * License: http://www.apache.org/licenses/LICENSE-2.0
 */
package com.spacepirates.logging.jui;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;

/**
 *
 * @author Scott Douglass
 */
public class CSVFormatter extends Formatter {

  private final SimpleDateFormat timestamp =
    new SimpleDateFormat("yyyy-MM-dd,HH:mm:ss");
  private static final String COL_SEP=",";
  private static final String QUOTE="\"";
  private static final String EOL=System.getProperty("line.separator");

  /**
   * Format the LogRecord as a single line, with comma separated values.
   * <pre>
   * ConsoleHandler handler = new ConsoleHandler();
   * handler.setFormatter(new CSVFormatter());
   * LOG.addHandler(handler);
   * LOG.setUseParentHandlers(false);
   * </pre>
   *
   * @param lr the LogRecord
   * @return the formatted message
   */
  @Override
  public String format(final LogRecord lr) {
    final StringBuilder message = new StringBuilder();
    synchronized(timestamp) {
      message.append(timestamp.format(new Date(lr.getMillis())));
    }
    message.append(COL_SEP);
    message.append(lr.getLevel().getName());
    message.append(COL_SEP);
    message.append(QUOTE);
    message.append(formatMessage(lr));
    message.append(QUOTE);
    message.append(COL_SEP);
    message.append(lr.getSourceClassName());
    message.append(COL_SEP);
    message.append(lr.getSourceMethodName());
    message.append(EOL);
    return message.toString();
  }

}
}]