/**
 * 
 */


package gov.va.med.cds.aspects.exception;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * Class that logs the exception to either a set logger or the default class logger
 *  
 * @author susarlan
 *
 */
public class LogAspect
{
    // Logger available to sub classes
    protected final Log logger = LogFactory.getLog( getClass() );

    private Log errorLogger;


    /**
     * Set the logger to which the exception should be logged as an error
     * You can alternatively override the logException method
     * to perform custom logging in derived classes
     * 
     * @param errorLoggerName - logger category to which exception should be logged as an error
     */
    public void setErrorLogger( String errorLoggerName )
    {
        this.errorLogger = LogFactory.getLog( errorLoggerName );
    }


    /***
     * Log the given exception at an error level provided the errorLogger
     * has been set up through the setErrorLogger(...) property
     * If the errorLogger has not been setup, uses as default
     * the logger declared in this class for logging the errors.
     * Calls buildMessage in order to determine the concrete message to log.
     * Always passes the full exception to the log
     * 
     * @param exception - exception that was thrown during the handling of the request
     */
    protected void logException( Throwable exception )
    {
        if ( errorLogger == null || !errorLogger.isErrorEnabled() )
        {
            errorLogger = logger;
        }

        // log the error
        errorLogger.error( buildErrorMessage( exception ), exception );
    }


    /***
     * Build a log message for the exception that occurred during the processing of a request
     * 
     * @param exception - exception that was thrown during the handling of the request
     * @return String - the log message to use
     */
    protected String buildErrorMessage( Throwable exception )
    {
        String msg = exception.getMessage();
        return "Request handling resulted in exception" + ( ( msg != null && msg.length() > 0 ) ? ( " - " + msg ) : "" );
    }
}
