/**
 * Copyright 2012 Netflix, Inc.
 *
 * 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 com.netflix.hystrix.contrib.requestservlet;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.netflix.hystrix.HystrixRequestLog;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;

/**
 * Log an INFO message with the output from <code>HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()</code> at the end of each requet.
 * <p>
 * A pre-requisite is that {@link HystrixRequestContext} is initialized, such as by using {@link HystrixRequestContextServletFilter}.
 * <p>
 * Install by adding the following lines to your project web.xml:
 * <p>
 * 
 * <pre>
 * {@code
 *   <filter>
 *     <display-name>HystrixRequestLogViaLoggerServletFilter</display-name>
 *     <filter-name>HystrixRequestLogViaLoggerServletFilter</filter-name>
 *     <filter-class>com.netflix.hystrix.contrib.requestservlet.HystrixRequestLogViaLoggerServletFilter</filter-class>
 *   </filter>
 *   <filter-mapping>
 *     <filter-name>HystrixRequestLogViaLoggerServletFilter</filter-name>
 *     <url-pattern>/*</url-pattern>
 *   </filter-mapping>
 * }
 * </pre>
 * <p>
 * NOTE: This filter must complete before {@link HystrixRequestContext} is shutdown otherwise the {@link HystrixRequestLog} will already be cleared.
 * <p>
 * This will output a log line similar to this:
 * 
 * <pre>
 * Hystrix Executions [POST /order] => CreditCardCommand[SUCCESS][1122ms]
 * </pre>
 */
public class HystrixRequestLogViaLoggerServletFilter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(HystrixRequestLogViaLoggerServletFilter.class);

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        StringBuilder requestURL = new StringBuilder();
        try {
            // get the requested URL for our logging so it can be associated to a particular request
            String uri = ((HttpServletRequest) request).getRequestURI();
            String queryString = ((HttpServletRequest) request).getQueryString();
            String method = ((HttpServletRequest) request).getMethod();
            requestURL.append(method).append(" ").append(uri);
            if (queryString != null) {
                requestURL.append("?").append(queryString);
            }
            chain.doFilter(request, response);
        } finally {
            try {
                if (HystrixRequestContext.isCurrentThreadInitialized()) {
                    HystrixRequestLog log = HystrixRequestLog.getCurrentRequest();
                    logger.info("Hystrix Executions [{}] => {}", requestURL.toString(), log.getExecutedCommandsAsString());
                }
            } catch (Exception e) {
                logger.warn("Unable to append HystrixRequestLog", e);
            }

        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }
}
