/* ======================================================================
   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 javax.servlet.ServletContext;

import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;

/**
 * Class to log all messages through the ServletContext log. 
 * This provides a nicer way todo logging by default in a servlet enviroment that 
 * sending it to the console. 
 * @author buckett
 */
public class ServletAppender extends AppenderSkeleton
{

    ServletContext context;
    
    /**
     * Need to pass in the ServletContext which we will log against.
     * As we need a context object to do any logging this appender can't
     * be setup from a properties file.
     */
    public ServletAppender(ServletContext context)
    {
        super();
        this.context = context;
    }

    /**
     * Logs the event through the ServletContext.log methods.
     * @see org.apache.log4j.AppenderSkeleton#append(org.apache.log4j.spi.LoggingEvent)
     */
    protected void append(LoggingEvent event)
    {
        if (event.getThrowableInformation() != null)
        {
            context.log(event.getRenderedMessage(), event.getThrowableInformation().getThrowable());
        }
        else
        {
            context.log(event.getRenderedMessage());
        }

    }

    /**
     * Need to have a layout.
     * @see org.apache.log4j.Appender#requiresLayout()
     */
    public boolean requiresLayout()
    {
        return true;
    }

    /**
     * Called at closure. Don't need to do anything.
     * @see org.apache.log4j.Appender#close()
     */
    public void close()
    {
        
    }

}
