/* ------------------------------------------------------------------------
 * $Id$
 * Copyright 2007 Tim Vernum
 * ------------------------------------------------------------------------
 * 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.adjective.useful.log4j;

import org.apache.log4j.PatternLayout;
import org.apache.log4j.spi.LocationInfo;
import org.apache.log4j.spi.LoggingEvent;

/**
 * This is an alternative to the {@link PatternLayout} in log4j.
 * <br>
 * This class filters the stack trace (i.e. patterns %C, %M, %L, and %F) to exclude any reference to
 * the following classes:<UL>
 * <LI><code>org.slf4j.*</code></LI>
 * <LI><code>org.apache.log4j.*</code></LI>
 * <LI><code>org.apache.commons.logging.*</code></LI>
 * </UL>
 * This solution allows for the correct use of these patterns when <A href="http://www.slf4j.org/">slf4j</A>
 *  is masquerading as <A href="http://jakarta.apache.org/commons/logging/">jakarta-commons-logging</A>.
 * <p>
 * <b>Usage:</b>This class can be used anywhere where {@link PatternLayout} would have been used. Simple add this
 *  class to the same classpath as the log4j jar, and modify your configuration to reference
 * <code>org.adjective.useful.log4j.Slf4jFilteringPatternLayout</code> instead of <code>PatternLayout</code>.
 * <br>
 * (<i>Note:</i> Special classpath haqndling will be required in an OSGi environment, the configuration of which
 *  is beyond the scope of this documentation)
 * <p>
 * <b>IMPORTANT NOTE:</b> Due to the architecture of log4j 1.2, use of this layout has a <i>global</i> effect. 
 * The layout will change the state of the {@link LoggingEvent} in order to filter the above-mentioned classes, 
 * which will affect all subsequent processing of that event. For configurations where there is a single log 
 * file this should not present a problem. If you need to log to multiple appenders, with different layouts,
 * then you may need to pay attention to the ordering of the appenders within your configuration, in order to 
 * acheive the desired result.
 * @version $Revision$
 */
public class Slf4jFilteringPatternLayout extends PatternLayout
{
    public Slf4jFilteringPatternLayout()
    {
        super();
    }

    public Slf4jFilteringPatternLayout(String pattern)
    {
        super(pattern);
    }

    public String format(LoggingEvent event)
    {
        filterLocation(event);
        return super.format(event);
    }

    private void filterLocation(LoggingEvent event)
    {
        LocationInfo location = event.getLocationInformation();
        if (location.fullInfo == null)
        {
            return;
        }
        // Use a trailing "#" to mark that we've already reset the location.
        // Generating a stack trace each time is expensive, and the way log4j (1.2.14)
        // parses the stack trace ignores trailing characters.
        if (location.fullInfo.endsWith("#"))
        {
            return;
        }
        StackTraceElement caller = getCallingLocation(event);
        if (caller == null)
        {
            location.fullInfo += " #";
        }
        else
        {
            location.fullInfo = caller.toString() + " #";
        }
    }

    private StackTraceElement getCallingLocation(LoggingEvent event)
    {
        StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
        boolean foundCaller = false;
        for (int i = 0; i < stackTrace.length; i++)
        {
            if (!foundCaller)
            {
                if (stackTrace[i].getClassName().equals(event.fqnOfCategoryClass))
                {
                    foundCaller = true;
                }
                continue;
            }
            if (isFiltered(stackTrace[i]))
            {
                continue;
            }
            return stackTrace[i];
        }
        return null;
    }

    private boolean isFiltered(StackTraceElement element)
    {
        String className = element.getClassName();
        if (className.startsWith("org.slf4j")
                || className.startsWith("org.apache.commons.logging")
                || className.startsWith("org.apache.log4j"))
        {
            return true;
        }
        return false;
    }
}
