/*
 * $Id: VKCFormatter.java,v 1.9 2005/01/03 18:21:13 marbobo Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log: VKCFormatter.java,v $
 * Revision 1.9  2005/01/03 18:21:13  marbobo
 * + ContextPath nicht anzeigen falls nicht vorhanden (Betrifft z.B. Konverterserver)
 *
 * Revision 1.8  2004/12/22 14:24:08  jonyp
 * added display of contextpath
 *
 * Revision 1.7  2004/12/20 13:33:59  marbobo
 * + kleine visuelle Anpassung
 *
 * Revision 1.6  2004/11/10 15:02:46  koppy
 * Projektweite Überarbeitung von Error-Logs, Stacktraces,..
 *
 */

package vkc.misc;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;

import vkc.util.StringUtils;
import vkc.view.WebShare;

/**
 * Schreibt den Log Record in dem fuer das VKC benoetigten Format.
 */

public class VKCFormatter extends Formatter {
  private String timeStampFormat = "dd.MM.yyyy/HH:mm:ss.SSS: ";

  public void setTimeStampFormat( String format ) {
      timeStampFormat = format;	 
  }

  public String getTimeStampFormat() {
  	  return timeStampFormat;
  }

  public String format( LogRecord logRecord ) {
	  StringBuffer buf = new StringBuffer();
      SimpleDateFormat formatter = new SimpleDateFormat( timeStampFormat );

      Date currentTime = new Date();
	  String dateString = formatter.format( currentTime );
      
	  buf.append( dateString );
      
      buf.append( " [" + logRecord.getLevel() + "] ");
     
      if ( !StringUtils.isEmpty( WebShare.getContextPath() ) ) {
          buf.append( " [" + WebShare.getContextPath() + "] ");
      }
      
      if ( logRecord.getSourceClassName() != null ) {
		  buf.append( "(" + logRecord.getSourceClassName()+ ")" );
      }
      
      if ( logRecord.getSourceMethodName() != null ) {
	      buf.append( " - " + logRecord.getSourceMethodName() );
      }
      
      if ( logRecord.getMessage() != null ) {
	      buf.append( logRecord.getMessage() );
      }
      
      if ( logRecord.getThrown() != null ) {
            buf.append( "\n" );
            
            try {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter( sw );
                logRecord.getThrown().printStackTrace( pw );
                pw.close();
                buf.append( sw.toString() );
            } catch ( Exception ex ) {
            }
      }
        
      buf.append( "\n" );
	     
      return buf.toString();
    }
  
	public synchronized String formatMessage( LogRecord record ) {
		return record.getMessage();
	}
}