1、手写一个过滤器


import cn.hutool.core.util.IdUtil;
import org.slf4j.MDC;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class MDCInsertingFilter extends OncePerRequestFilter {


    public final static String TRACE_ID = "traceId";

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {

        insertIntoMDC(httpServletRequest);
        try {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
        } finally {
            clearMDC();
        }
    }

    void insertIntoMDC(ServletRequest request) {

        MDC.put(TRACE_ID, IdUtil.objectId());
    }

    void clearMDC() {

        MDC.remove(TRACE_ID);
    }

}

2、在web.xml配置过滤器

<filter>
		<filter-name>MDCInsertingFilter</filter-name>
		<filter-class>com.tgjf.pay.web.filter.MDCInsertingFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>MDCInsertingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

3、log4j.properties  输出日志

添加  

%X{traceId}

 例子:1、手写一个过滤器-LMLPHP

04-16 23:25