SpringCloud微服务之OpenFeign添加traceId全链路监控
注册中心请参考:https://blog.csdn.net/MadLifeBin/article/details/120332483可搭建单机版用于 Demo 测试服务提供与消费请参考:https://blog.csdn.net/MadLifeBin/article/details/120420139全链路监控添加日志支持maven添加依赖版本参考父POM<dependency><
·
注册中心
请参考:https://blog.csdn.net/MadLifeBin/article/details/120332483
可搭建单机版用于 Demo 测试
服务提供与消费
请参考:https://blog.csdn.net/MadLifeBin/article/details/120420139
全链路监控
添加日志支持
maven添加依赖
版本参考父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>
服务双方添加日志配置文件
服务双方增加过滤器为每个请求创建traceId
启动类增加注解@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.
consumer配置OpenFeign透传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
根据traceId追踪日志
- 启动Eureka、Provider、Consumer
- 浏览器调用接口,在浏览器控制台拿到traceId
- 分别去对应服务的日志查找具体日志行。
若搭配上阿里云的 SLS 或者 自行搭建的 EFLK,全链路日志只会更加方便
更多推荐
已为社区贡献1条内容
所有评论(0)