没有使用链路跟踪时,页面报错都是要到日志里定位,在分布式部署的项目中,还是比较麻烦的。项目中链路跟踪本人选型了skywalking,为了方便定位页面问题,实现了web界面reponse中返回skywalking的traceId,不多说直接上代码实现。
1、pom.xml引入
<dependency>
<groupId>org.apache.skywalking</groupId>
<artifactId>apm-toolkit-trace</artifactId>
<version>8.7.0</version>
</dependency>
2、TraceResponseFilter.java
package net.grandhonor.framework.boot.tools.skywalking;
import org.apache.skywalking.apm.toolkit.trace.TraceContext;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 设置skywalking的traceId到response请求头
*
* @author wangfenglei
*/
@ConditionalOnProperty(value = "grandhonor.base.tools.skywalking.switch", havingValue = "true", matchIfMissing = false)
@Component
public class TraceResponseFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
FilterChain filterChain) throws ServletException, IOException {
try{
//设置skywalking的traceId
httpServletResponse.addHeader("traceId", TraceContext.traceId());
}catch (Exception e){}
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
}
说明:本人对常见的中间件做了封装,skywalking也设置了开启开关,通过@ConditionalOnProperty控制,只有开关打开配置才生效。
3、效果展示
?
?
?
|