Commit e351cdf7850b2af4de5927e0ba2514451457e701

Authored by YunaiV
1 parent 81b1f375

完善 skywalking 组件的集成

... ... @@ -196,6 +196,11 @@
196 196 <artifactId>apm-toolkit-logback-1.x</artifactId>
197 197 <version>${skywalking.version}</version>
198 198 </dependency>
  199 + <dependency>
  200 + <groupId>org.apache.skywalking</groupId>
  201 + <artifactId>apm-toolkit-opentracing</artifactId>
  202 + <version>${skywalking.version}</version>
  203 + </dependency>
199 204  
200 205 <dependency>
201 206 <groupId>de.codecentric</groupId>
... ...
src/main/java/cn/iocoder/dashboard/framework/tracer/config/TracerAutoConfiguration.java
1 1 package cn.iocoder.dashboard.framework.tracer.config;
2 2  
3   -import cn.iocoder.dashboard.framework.tracer.core.annotation.BizTracingAop;
  3 +import cn.iocoder.dashboard.framework.tracer.core.aop.BizTraceAspect;
  4 +import cn.iocoder.dashboard.framework.tracer.core.filter.TraceFilter;
  5 +import cn.iocoder.dashboard.framework.web.core.enums.FilterOrderEnum;
  6 +import io.opentracing.Tracer;
  7 +import org.apache.skywalking.apm.toolkit.opentracing.SkywalkingTracer;
4 8 import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
5 9 import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
6 10 import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
7 11 import org.springframework.boot.context.properties.EnableConfigurationProperties;
  12 +import org.springframework.boot.web.servlet.FilterRegistrationBean;
8 13 import org.springframework.context.annotation.Bean;
9 14 import org.springframework.context.annotation.Configuration;
10 15  
... ... @@ -14,21 +19,38 @@ import org.springframework.context.annotation.Configuration;
14 19 * @author mashu
15 20 */
16 21 @Configuration
17   -@ConditionalOnClass({BizTracingAop.class})
18   -@EnableConfigurationProperties(BizTracerProperties.class)
  22 +@ConditionalOnClass({BizTraceAspect.class})
  23 +@EnableConfigurationProperties(TracerProperties.class)
19 24 @ConditionalOnProperty(prefix = "yudao.tracer", value = "enable", matchIfMissing = true)
20 25 public class TracerAutoConfiguration {
21 26  
22 27 @Bean
23 28 @ConditionalOnMissingBean
24   - public BizTracerProperties bizTracerProperties() {
25   - return new BizTracerProperties();
  29 + public TracerProperties bizTracerProperties() {
  30 + return new TracerProperties();
26 31 }
27 32  
28 33 @Bean
29 34 @ConditionalOnMissingBean
30   - public BizTracingAop bizTracingAop() {
31   - return new BizTracingAop();
  35 + public BizTraceAspect bizTracingAop() {
  36 + return new BizTraceAspect();
  37 + }
  38 +
  39 + @Bean
  40 + @ConditionalOnMissingBean
  41 + public Tracer tracer() {
  42 + return new SkywalkingTracer();
  43 + }
  44 +
  45 + /**
  46 + * 创建 TraceFilter 过滤器,响应 header 设置 traceId
  47 + */
  48 + @Bean
  49 + public FilterRegistrationBean<TraceFilter> traceFilter() {
  50 + FilterRegistrationBean<TraceFilter> registrationBean = new FilterRegistrationBean<>();
  51 + registrationBean.setFilter(new TraceFilter());
  52 + registrationBean.setOrder(FilterOrderEnum.TRACE_FILTER);
  53 + return registrationBean;
32 54 }
33 55  
34 56 }
... ...
src/main/java/cn/iocoder/dashboard/framework/tracer/config/BizTracerProperties.java renamed to src/main/java/cn/iocoder/dashboard/framework/tracer/config/TracerProperties.java
... ... @@ -10,5 +10,5 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
10 10 */
11 11 @ConfigurationProperties("yudao.tracer")
12 12 @Data
13   -public class BizTracerProperties {
  13 +public class TracerProperties {
14 14 }
... ...
src/main/java/cn/iocoder/dashboard/framework/tracer/core/annotation/BizTracing.java renamed to src/main/java/cn/iocoder/dashboard/framework/tracer/core/annotation/BizTrace.java
... ... @@ -10,7 +10,7 @@ import java.lang.annotation.*;
10 10 @Target({ElementType.METHOD})
11 11 @Retention(RetentionPolicy.RUNTIME)
12 12 @Inherited
13   -public @interface BizTracing {
  13 +public @interface BizTrace {
14 14  
15 15 /**
16 16 * 业务编号 tag 名
... ... @@ -22,6 +22,11 @@ public @interface BizTracing {
22 22 String TYPE_TAG = "biz.type";
23 23  
24 24 /**
  25 + * @return 操作名
  26 + */
  27 + String operationName() default "";
  28 +
  29 + /**
25 30 * @return 业务编号
26 31 */
27 32 String id();
... ...
src/main/java/cn/iocoder/dashboard/framework/tracer/core/annotation/BizTracingAop.java deleted
1   -package cn.iocoder.dashboard.framework.tracer.core.annotation;
2   -
3   -import cn.hutool.core.util.StrUtil;
4   -import cn.iocoder.dashboard.util.sping.SpElUtil;
5   -import lombok.extern.slf4j.Slf4j;
6   -import org.apache.skywalking.apm.toolkit.trace.ActiveSpan;
7   -import org.aspectj.lang.ProceedingJoinPoint;
8   -import org.aspectj.lang.annotation.Around;
9   -import org.aspectj.lang.annotation.Aspect;
10   -
11   -/**
12   - * 业务链路AOP切面
13   - *
14   - * @author mashu
15   - */
16   -@Aspect
17   -@Slf4j
18   -public class BizTracingAop {
19   -
20   - @Around(value = "@annotation(bizTracing)")
21   - public void tagBizInfo(ProceedingJoinPoint joinPoint, BizTracing bizTracing) {
22   - String bizId = (String) SpElUtil.analysisSpEl(bizTracing.id(), joinPoint);
23   - String bizType = (String) SpElUtil.analysisSpEl(bizTracing.type(), joinPoint);
24   - if (StrUtil.isBlankIfStr(bizId)) {
25   - log.error("empty biz: bizId[{}], bizType[{}].", bizId, bizType);
26   - return;
27   - }
28   - log.info("accept biz: bizId[{}], bizType[{}].", bizId, bizType);
29   - ActiveSpan.tag(BizTracing.ID_TAG, bizId);
30   - ActiveSpan.tag(BizTracing.TYPE_TAG, bizType);
31   - }
32   -}
src/main/java/cn/iocoder/dashboard/framework/tracer/core/aop/BizTraceAspect.java 0 → 100644
  1 +package cn.iocoder.dashboard.framework.tracer.core.aop;
  2 +
  3 +import cn.hutool.core.util.StrUtil;
  4 +import cn.iocoder.dashboard.framework.tracer.core.annotation.BizTrace;
  5 +import cn.iocoder.dashboard.util.sping.SpElUtil;
  6 +import io.opentracing.Span;
  7 +import io.opentracing.Tracer;
  8 +import lombok.extern.slf4j.Slf4j;
  9 +import org.aspectj.lang.ProceedingJoinPoint;
  10 +import org.aspectj.lang.annotation.Around;
  11 +import org.aspectj.lang.annotation.Aspect;
  12 +
  13 +import javax.annotation.Resource;
  14 +
  15 +/**
  16 + * {@link BizTrace} 切面,记录业务链路
  17 + *
  18 + * @author mashu
  19 + */
  20 +@Aspect
  21 +@Slf4j
  22 +public class BizTraceAspect {
  23 +
  24 + private static final String BIZ_OPERATION_NAME_PREFIX = "Biz/";
  25 +
  26 + @Resource
  27 + private Tracer tracer;
  28 +
  29 + @Around(value = "@annotation(trace)")
  30 + public Object around(ProceedingJoinPoint joinPoint, BizTrace trace) throws Throwable {
  31 + // 创建 span
  32 + String operationName = getOperationName(joinPoint, trace);
  33 + Span span = tracer.buildSpan(operationName).startManual();
  34 + try {
  35 + // 执行原有方法
  36 + return joinPoint.proceed();
  37 + } finally {
  38 + // 设置 Span 的 biz 属性
  39 + setBizTag(span, joinPoint, trace);
  40 + // 完成 Span
  41 + span.finish();
  42 + }
  43 + }
  44 +
  45 + private String getOperationName(ProceedingJoinPoint joinPoint, BizTrace trace) {
  46 + // 自定义操作名
  47 + if (StrUtil.isNotEmpty(trace.operationName())) {
  48 + return BIZ_OPERATION_NAME_PREFIX + trace.operationName();
  49 + }
  50 + // 默认操作名,使用方法名
  51 + return BIZ_OPERATION_NAME_PREFIX
  52 + + joinPoint.getSignature().getDeclaringType().getSimpleName()
  53 + + "/" + joinPoint.getSignature().getName();
  54 + }
  55 +
  56 + private void setBizTag(Span span, ProceedingJoinPoint joinPoint, BizTrace trace) {
  57 + try {
  58 + span.setTag(BizTrace.TYPE_TAG, StrUtil.toString(SpElUtil.analysisSpEl(trace.type(), joinPoint)));
  59 + span.setTag(BizTrace.ID_TAG, StrUtil.toString(SpElUtil.analysisSpEl(trace.id(), joinPoint)));
  60 + } catch (Exception ex) {
  61 + log.error("[around][解析 bizType 与 bizId 发生异常]", ex);
  62 + }
  63 + }
  64 +
  65 +}
... ...
src/main/java/cn/iocoder/dashboard/framework/tracer/core/filter/TraceFilter.java 0 → 100644
  1 +package cn.iocoder.dashboard.framework.tracer.core.filter;
  2 +
  3 +import cn.iocoder.dashboard.framework.tracer.core.util.TracerUtils;
  4 +import org.springframework.web.filter.OncePerRequestFilter;
  5 +
  6 +import javax.servlet.FilterChain;
  7 +import javax.servlet.ServletException;
  8 +import javax.servlet.http.HttpServletRequest;
  9 +import javax.servlet.http.HttpServletResponse;
  10 +import java.io.IOException;
  11 +
  12 +/**
  13 + * Trace 过滤器,打印 traceId 到 header 中返回
  14 + *
  15 + * @author 芋道源码
  16 + */
  17 +public class TraceFilter extends OncePerRequestFilter {
  18 +
  19 + /**
  20 + * Header 名 - 链路追踪编号
  21 + */
  22 + private static final String HEADER_NAME_TRACE_ID = "trace-id";
  23 +
  24 + @Override
  25 + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
  26 + throws IOException, ServletException {
  27 + // 设置响应 traceId
  28 + response.addHeader(HEADER_NAME_TRACE_ID, TracerUtils.getTraceId());
  29 + // 继续过滤
  30 + chain.doFilter(request, response);
  31 + }
  32 +
  33 +}
... ...
src/main/java/cn/iocoder/dashboard/framework/tracer/core/util/TracerUtils.java
... ... @@ -2,8 +2,6 @@ package cn.iocoder.dashboard.framework.tracer.core.util;
2 2  
3 3 import org.apache.skywalking.apm.toolkit.trace.TraceContext;
4 4  
5   -import java.util.UUID;
6   -
7 5 /**
8 6 * 链路追踪工具类
9 7 *
... ... @@ -18,10 +16,8 @@ public class TracerUtils {
18 16 }
19 17  
20 18 /**
21   - * 获得链路追踪编号
22   - * <p>
23   - * 直接返回skywalking 的TraceId 如果不存在的话为空字符串""
24   - * <p>
  19 + * 获得链路追踪编号,直接返回 SkyWalking 的 TraceId。
  20 + * 如果不存在的话为空字符串!!!
25 21 *
26 22 * @return 链路追踪编号
27 23 */
... ...
src/main/java/cn/iocoder/dashboard/framework/tracer/skywalking/LocalLogbackPatternConverter.java deleted
1   -/*
2   - * Licensed to the Apache Software Foundation (ASF) under one or more
3   - * contributor license agreements. See the NOTICE file distributed with
4   - * this work for additional information regarding copyright ownership.
5   - * The ASF licenses this file to You under the Apache License, Version 2.0
6   - * (the "License"); you may not use this file except in compliance with
7   - * the License. You may obtain a copy of the License at
8   - *
9   - * http://www.apache.org/licenses/LICENSE-2.0
10   - *
11   - * Unless required by applicable law or agreed to in writing, software
12   - * distributed under the License is distributed on an "AS IS" BASIS,
13   - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   - * See the License for the specific language governing permissions and
15   - * limitations under the License.
16   - *
17   - */
18   -
19   -
20   -package cn.iocoder.dashboard.framework.tracer.skywalking;
21   -
22   -import ch.qos.logback.classic.pattern.ClassicConverter;
23   -import ch.qos.logback.classic.spi.ILoggingEvent;
24   -import cn.iocoder.dashboard.framework.tracer.core.util.TracerUtils;
25   -
26   -/**
27   - * Created by mashu on 2021/3/6.
28   - */
29   -public class LocalLogbackPatternConverter extends ClassicConverter {
30   - /**
31   - * 作为默认的方式, 从{@link TracerUtils}中获取traceId,
32   - * 需要用这个去替代logback的Layout,
33   - * 同时避免了sky-walking agent生效的情况下仍然输出定值的问题.
34   - *
35   - * @param iLoggingEvent the event
36   - * @return the traceId: UUID, or the real traceId.
37   - */
38   - @Override
39   - public String convert(ILoggingEvent iLoggingEvent) {
40   - return TracerUtils.getTraceId();
41   - }
42   -}
src/main/java/cn/iocoder/dashboard/framework/tracer/skywalking/TraceIdPatternLogbackLayout.java deleted
1   -/*
2   - * Licensed to the Apache Software Foundation (ASF) under one or more
3   - * contributor license agreements. See the NOTICE file distributed with
4   - * this work for additional information regarding copyright ownership.
5   - * The ASF licenses this file to You under the Apache License, Version 2.0
6   - * (the "License"); you may not use this file except in compliance with
7   - * the License. You may obtain a copy of the License at
8   - *
9   - * http://www.apache.org/licenses/LICENSE-2.0
10   - *
11   - * Unless required by applicable law or agreed to in writing, software
12   - * distributed under the License is distributed on an "AS IS" BASIS,
13   - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   - * See the License for the specific language governing permissions and
15   - * limitations under the License.
16   - *
17   - */
18   -
19   -
20   -package cn.iocoder.dashboard.framework.tracer.skywalking;
21   -
22   -import ch.qos.logback.classic.PatternLayout;
23   -
24   -/**
25   - * Based on the logback-component convert register mechanism,
26   - * register {@link LocalLogbackPatternConverter} as a new convert, match to "tid".
27   - * You can use "%tid" in logback config file, "Pattern" section.
28   - * If sky-walking agent is not active mode, it will use UUID as tid.
29   - * <p>
30   - * logback 的转换组件,为tid 添加占位符的转换器
31   - * Created by mashu on 2021/3/6.
32   - */
33   -public class TraceIdPatternLogbackLayout extends PatternLayout {
34   - static {
35   - defaultConverterMap.put("tid", LocalLogbackPatternConverter.class.getName());
36   - }
37   -}
src/main/java/cn/iocoder/dashboard/framework/web/core/enums/FilterOrderEnum.java
... ... @@ -9,6 +9,7 @@ public interface FilterOrderEnum {
9 9  
10 10 int CORS_FILTER = Integer.MIN_VALUE;
11 11  
  12 + int TRACE_FILTER = CORS_FILTER + 1;
12 13  
13 14 int REQUEST_BODY_CACHE_FILTER = Integer.MIN_VALUE + 500;
14 15  
... ...
src/main/java/cn/iocoder/dashboard/modules/system/controller/auth/SysAuthController.java
... ... @@ -3,6 +3,7 @@ package cn.iocoder.dashboard.modules.system.controller.auth;
3 3 import cn.iocoder.dashboard.common.enums.CommonStatusEnum;
4 4 import cn.iocoder.dashboard.common.pojo.CommonResult;
5 5 import cn.iocoder.dashboard.framework.logger.operatelog.core.annotations.OperateLog;
  6 +import cn.iocoder.dashboard.framework.tracer.core.annotation.BizTrace;
6 7 import cn.iocoder.dashboard.modules.system.controller.auth.vo.auth.SysAuthLoginReqVO;
7 8 import cn.iocoder.dashboard.modules.system.controller.auth.vo.auth.SysAuthLoginRespVO;
8 9 import cn.iocoder.dashboard.modules.system.controller.auth.vo.auth.SysAuthMenuRespVO;
... ... @@ -58,6 +59,7 @@ public class SysAuthController {
58 59  
59 60 @GetMapping("/get-permission-info")
60 61 @ApiOperation("获取登陆用户的权限信息")
  62 + @BizTrace(id = "1", type = "'user'")
61 63 public CommonResult<SysAuthPermissionInfoRespVO> getPermissionInfo() {
62 64 // 获得用户信息
63 65 SysUserDO user = userService.getUser(getLoginUserId());
... ...
src/main/resources/logback-spring.xml
1   -<configuration>   
  1 +<configuration>  
  2 +  
2 3 <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">     
3 4 <encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
4   - <layout class="cn.iocoder.dashboard.framework.tracer.skywalking.TraceIdPatternLogbackLayout">
  5 + <layout class="org.apache.skywalking.apm.toolkit.log.logback.v1.x.TraceIdPatternLogbackLayout">
5 6 <pattern>%d{ISO8601} | %tid | %thread | %-5level | %msg%n</pattern>
6 7 </layout>
7 8 </encoder>
8 9 </appender>
  10 +
9 11 <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
10 12 <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
11 13 <FileNamePattern>./logs/ruoyi-vue-pro-%d{yyyy-MM-dd_HH}.log</FileNamePattern>
... ... @@ -20,13 +22,20 @@
20 22 <MaxFileSize>10MB</MaxFileSize>
21 23 </triggeringPolicy>
22 24 </appender>
  25 +
23 26 <appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender">
24 27 <discardingThreshold>0</discardingThreshold>
25 28 <queueSize>10</queueSize>
26 29 <appender-ref ref="FILE"/>
27 30 </appender>
  31 +
28 32 <!-- skywalking grpc 日志收集 8.4.0版本开始支持 -->
29 33 <appender name="GRPC" class="org.apache.skywalking.apm.toolkit.log.logback.v1.x.log.GRPCLogClientAppender">
  34 + <encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
  35 + <layout class="org.apache.skywalking.apm.toolkit.log.logback.v1.x.mdc.TraceIdMDCPatternLogbackLayout">
  36 + <Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%X{tid}] [%thread] %-5level %logger{36} -%msg%n</Pattern>
  37 + </layout>
  38 + </encoder>s
30 39 </appender>
31 40  
32 41 <springProfile name="dev">
... ... @@ -35,12 +44,14 @@
35 44 <appender-ref ref="ASYNC"/>
36 45 </logger>
37 46 </springProfile>
  47 +
38 48 <springProfile name="local">
39 49 <logger name="cn.iocoder.dashboard" level="INFO" additivity="false">
40 50 <appender-ref ref="STDOUT"/>
41 51 <appender-ref ref="GRPC"/>
42 52 </logger>
43 53 </springProfile>
  54 +
44 55 <springProfile name="default">
45 56 <logger name="cn.iocoder.dashboard" level="INFO" additivity="false">
46 57 <appender-ref ref="STDOUT"/>
... ... @@ -48,7 +59,7 @@
48 59 </logger>
49 60 </springProfile>
50 61  
51   - <root level="DEBUG">      
  62 + <root level="INFO">      
52 63 <appender-ref ref="STDOUT"/>   
53 64 <appender-ref ref="ASYNC"/> 
54 65 </root>
... ... @@ -56,4 +67,4 @@
56 67 <logger name="cn.iocoder.dashboard" level="INFO">
57 68 <appender-ref ref="STDOUT"/>
58 69 </logger>
59   -</configuration>
60 70 \ No newline at end of file
  71 +</configuration>
... ...