一、手寫一個過濾器
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); } }
二、在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>
三、log4j.properties 輸出日誌
添加 html
%X{traceId}
例子:java