//-------------------------------------------------------------------------------------------------
// Module    : $RCSfile: TestLogger.java,v $
// Version   : $Revision: 0.0 $  $Author: Patrick $  $Date: 26.11.2011 15:26:38 $
// Project   : TaskTreePerformanceTest
// Creation  : 2011 by Patrick
// Copyright : Patrick Harms, 2011
//-------------------------------------------------------------------------------------------------

package de.ugoe.cs.quest.tasktrees.testutils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;


//-------------------------------------------------------------------------------------------------
/**
 * TODO comment
 *
 * @version $Revision: $ $Date: $
 * @author  2011, last modified by $Author: $
 */
//-------------------------------------------------------------------------------------------------

public class SimpleLogFormatter extends Formatter
{
  //-----------------------------------------------------------------------------------------------
  /**
   *
   */
  //-----------------------------------------------------------------------------------------------
  @Override
  public String format(LogRecord record)
  {
    StringBuffer result = new StringBuffer();
    result.append(record.getLevel().getName().charAt(0));
    result.append(" | ");
    result.append(new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss,SSS").format(record.getMillis()));
    result.append(" | ");
    tailValue("" + record.getThreadID(), 6, result);
    result.append(" | ");
    tailValue(record.getLoggerName(), 30, result);
    result.append(" | ");
    result.append(record.getMessage());
    
    if (record.getThrown() != null)
    {
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      record.getThrown().printStackTrace(new PrintStream(out));
      result.append("\n");
      result.append(out.toString());
      try
      {
        out.close();
      }
      catch (IOException e)
      {
        // ignore
      }
    }
    
    result.append("\n");
    
    return result.toString();
  }
  
  //-----------------------------------------------------------------------------------------------
  /**
   *
   */
  //-----------------------------------------------------------------------------------------------
  private void tailValue(String value, int length, StringBuffer output)
  {
    for (int i = value.length() - length - 1; i < value.length(); i++)
    {
      if (i < 0)
      {
        output.append(" ");
      }
      else
      {
        output.append(value.charAt(i));
      }
    }
  }
}
