/*
 * Created on 13-Apr-2005
 */
package org.bodington.logging;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;

import org.apache.log4j.helpers.DateLayout;
import org.apache.log4j.spi.LoggingEvent;

/**
 * A simple layout that adds in the exception stack trace.
 * This is build onto of DateLayout so we can use that for formatting the
 * dates.
 * @author buckett
 */
public class SimpleThrowableLayout extends DateLayout
{

    /**
     * Format the log message.
     * @param event The logging event.
     * @return The formatted log message.
     * @see org.apache.log4j.Layout#format(org.apache.log4j.spi.LoggingEvent)
     */
    public String format(LoggingEvent event)
    {
        StringBuffer buffer = new StringBuffer();
        Throwable throwable;
        
        dateFormat(buffer, event);
        buffer.append(" ");
        buffer.append(event.getLevel().toString());
        buffer.append(" ");
        buffer.append(event.getLoggerName());
        buffer.append(" - ");
        buffer.append(event.getMessage());
        buffer.append("\n");
        if(event.getThrowableInformation() != null)
        {
            throwableFormat(buffer, event.getThrowableInformation().getThrowable());
        }
        return buffer.toString();
    }
    
    /**
     * Writes the exception stack trace to the buffer.
     * @param buffer The buffer which we append the stack trace.
     * @param throwable The throwable object to get the stack trace from.
     */
    public void throwableFormat(StringBuffer buffer, Throwable throwable)
    {
        if(throwable != null){
            ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
            PrintWriter printWriter = new PrintWriter(byteArray);
            throwable.printStackTrace(printWriter);
            printWriter.flush();
            buffer.append(byteArray);
        }
    }

    /**
     * We actually print out stack traces when things go wrong.
     * @see org.apache.log4j.Layout#ignoresThrowable()
     */
    public boolean ignoresThrowable()
    {
        return false;
    }

}
