一,为什么需要trace-id
我们搭建了SkyWalking服务,我们需要在日志中记录下来每次请求的唯一标识(trace-id),在我们微服务调用过程中,可以通过trace-id来追踪整个链路的日志,从而更快的定位问题。
二,配置过程
2.1, pom文件加入:
<dependency>
<groupId>org.apache.skywalking</groupId>
<artifactId>apm-toolkit-logback-1.x</artifactId>
<version>${skywalking.version}</version>
</dependency>
<dependency>
<groupId>org.apache.skywalking</groupId>
<artifactId>apm-toolkit-trace</artifactId>
<version>${skywalking.version}</version>
</dependency>
2.2,重写TraceIdMDCPatternLogbackLayout类:
public class MyTraceIdMDCPatternLogbackLayout extends TraceIdMDCPatternLogbackLayout {
static {
defaultConverterMap.put("My", MyConverter.class.getName());
}
public static class MyConverter extends ClassicConverter {
private MyConverterCommand myConverterCommand;
@Override
public void start() {
super.start();
String[] key = OptionHelper.extractDefaultReplacement(this.getFirstOption());
if (key.length > 0 && "uuid".equals(key[0])) {
this.myConverterCommand = new UUIDCommand();
}
}
@Override
public String convert(ILoggingEvent iLoggingEvent) {
if (myConverterCommand != null) {
return myConverterCommand.convert(iLoggingEvent);
}
return "";
}
}
private interface MyConverterCommand {
String convert(ILoggingEvent loggingEvent);
}
private static class UUIDCommand implements MyConverterCommand {
@Override
public String convert(ILoggingEvent loggingEvent) {
return UUID.randomUUID().toString().replace("-", "");
}
}
}
2.3,在logback.xml中加入:
<property name="pattern"
value="|%property{serviceName}|${meta.ops.env:-null}:%property{instanceIP}:%property{instancePort}|%replace(%X{tid}){'TID:', ''}|%X{userId}|%My{uuid}|%d{yyyyMMddHHmmssSSS}|%thread|%level|%logger{36}:%line|%msg%n"/>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<layout class="cn.hydee.starter.log.MyTraceIdMDCPatternLogbackLayout">
<pattern>
${pattern}
</pattern>
</layout>
</appender>
三,启动服务
启动服务的时候Java只需要在VM options中追加格式为:
-javaagent:/path/to/path/skywalking-agent.jar
-Dskywalking.agent.service_name=YOUR_APP_NAME
-Dskywalking.collector.backend_service=OAP_SEVER_HOST:gRPC_PORT
当我们请求接口时候,在打印日志的时候就会有一个uuid,通过uuid我们可以追踪整个链路。
除了skywalking还有sleuth同样也可以实现链路追踪。