package com.esv.freight.file.common.filter;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.UUID;

/**
 * @description: 处理Logback traceId过滤器
 * @project: SpringCloudTemplate
 * @name: com.esv.springcloud.template.common.filter.LogbackFilter
 * @author: 黄朝斌
 * @email: huangchaobin@esvtek.com
 * @createTime: 2020/03/13 11:35
 * @version:1.0
 */
@Slf4j
public class LogbackFilter implements Filter {

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

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 获取来自上游服务的传参traceId
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String traceId = httpServletRequest.getHeader("gateway_traceid");
        boolean bInsertMDC = setMDC(traceId);
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            if(bInsertMDC) {
                MDC.remove("traceId");
            }
        }
    }

    @Override
    public void destroy() {

    }

    private boolean setMDC(String traceId) {
        if (StringUtils.isEmpty(traceId) || "null".equalsIgnoreCase(traceId)) {
            traceId = UUID.randomUUID().toString().replace("-", "");
        }
        MDC.put("traceId", traceId);
        return true;
    }
}
