原文网址:SkyWalking–打印traceId到日志/获取traceId_IT利刃出鞘的博客-CSDN博客
简介
本处,我的skywalking服务端版本为8.7.0.
打印traceId到日志
简介
Skywalking可以直接在界面上看执行的链路,也可以将traceId输出到日志,这样的话,在日志里就可以分辨哪些是同一个请求。
本处,我使用logback,只配置将traceId日志输出到控制台,实际也可以写到日志文件的,方法差不多。logback配置方法见:
Java日志–logback–配置/介绍/基础_IT利刃出鞘的博客-CSDN博客
Java日志–logback–SpringBoot–整合/使用/教程/实例_IT利刃出鞘的博客-CSDN博客
实例
pom.xml
org.apache.skywalking
apm-toolkit-logback-1.x
8.7.0
logback-spring.xml(放到resources目录下)
添加此配置
[%tid] ${CONSOLE_LOG_PATTERN:-%clr(%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd HH:mm:ss.SSS}}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---) {faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}
- 使用[%tid] 来占trace-id的位置,默认为TID:N/A,当有请求调用时,会显示trace-id。
所有配置
[%tid] ${CONSOLE_LOG_PATTERN:-%clr(%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd HH:mm:ss.SSS}}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---) {faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}
启动结果

可以发现,没有请求的时候,打印的是:[TID:N/A],有请求进来时,打印traceId
代码中获取traceId
其他网址
skywalking获取traceId(tid)的方式_lijunwyf的专栏-CSDN博客
skywalking04 – skywalking自定义链路追踪@Trace_过了这个村没这个老王的博客-CSDN博客
简介
我们可以在代码中获取到traceId,这样一来,我们可以做如下操作:
- 将traceId传给前端。
- 将traceId连同本次请求的信息记录到操作日志中
有了traceId,我们就可以直接到skywalking的界面中根据traceId来搜索了:

用法
步骤1:在想获取traceId的地方加@Trace注解
例如:
@PostMapping("create") @Trace public Result create(Order order) { orderService.create(order); return new Result().message("创建订单成功"); }
Trace所在包:import org.apache.skywalking.apm.toolkit.trace.Trace;
步骤2:获得注解
例:
@PostMapping("create") @Trace public Result create(Order order) { orderService.create(order); String traceId = TraceContext.traceId(); return new Result().message("创建订单成功"); }
TraceContext所在包:import org.apache.skywalking.apm.toolkit.trace.TraceContext;
TraceContext可以获得spanId等其他信息:

项目应用
实际上,项目中不需要每个方法都加@Trace这个注解来获得traceId,只需要在全局响应的地方来获取即可。
下边展示项目中的实际用法(我是实测过的,可以获取到traceId)。
package com.example.common.advice; import com.example.common.entity.Result; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.apache.skywalking.apm.toolkit.trace.Trace; import org.apache.skywalking.apm.toolkit.trace.TraceContext; import org.springframework.core.MethodParameter; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; @Slf4j @ControllerAdvice public class GlobalResponseBodyAdvice implements ResponseBodyAdvice
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/204507.html原文链接:https://javaforall.net
