请参考:
https://blog.csdn.NET/MadLifeBin/article/details/120332483
可搭建单机版用于 Demo 测试
请参考:
https://blog.csdn.net/MadLifeBin/article/details/120420139
版本参考父POM
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
</dependency>
启动类增加注解@ServletComponentScan
@Order(1)
@WebFilter(urlPatterns = "/*",filterName = "traceIdFilter")
public class TraceIdFilter implements Filter {
public final static String MDC_TRACE_ID = "traceId";
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String traceId = httpRequest.getHeader(MDC_TRACE_ID);
if (StringUtils.isBlank(traceId)) {
traceId = IdUtil.fastSimpleUUID();;
}
MDC.put(MDC_TRACE_ID, traceId);
ThreadLocalUtils.setTraceId(traceId);
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setHeader(MDC_TRACE_ID, traceId);
chain.doFilter(request, response);
}
}
同时将traceId写回到response的header中,方便在前端获取traceId.
@Component
public class OpenFeignRequestInterceptor implements RequestInterceptor {
@Override
public void Apply(RequestTemplate requestTemplate) {
String traceId = MDC.get(TraceIdFilter.MDC_TRACE_ID);
requestTemplate.header(TraceIdFilter.MDC_TRACE_ID, traceId);
}
}
LOGGER.info("userId:{}",userId);
consumer
provider
若搭配上阿里云的 SLS 或者 自行搭建的 EFLK,全链路日志只会更加方便