/* ======================================================================
   Parts Copyright 2006 University of Leeds, Oxford University, University of the Highlands and Islands.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

====================================================================== */

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;
    }

}
