com.taotao.cloud.tracing.skywalking.interceptor.TraceInterceptor Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of taotao-cloud-starter-tracing-skywalking Show documentation
Show all versions of taotao-cloud-starter-tracing-skywalking Show documentation
taotao-cloud-starter-tracing-skywalking
/*
* Copyright (c) 2020-2030, Shuigedeng ([email protected] & https://blog.taotaocloud.top/).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.taotao.cloud.tracing.skywalking.interceptor;
import com.taotao.cloud.common.utils.common.IdGeneratorUtils;
import com.taotao.cloud.tracing.skywalking.ClusterTrace;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.skywalking.apm.toolkit.trace.TraceContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
public class TraceInterceptor implements HandlerInterceptor {
private static final Logger LOGGER = LoggerFactory.getLogger(TraceInterceptor.class);
public static final String TRACE_ID_HEADER = "Trace-Id";
private final ClusterTrace clusterTrace;
public TraceInterceptor(ClusterTrace clusterTrace) {
this.clusterTrace = clusterTrace;
}
/** skyWalking 未部署情况下的错误码 */
private static final String ERROR_STR = "Ignored_Trace,N/A";
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
String traceId = response.getHeader(TRACE_ID_HEADER) != null ? response.getHeader(TRACE_ID_HEADER) : "";
if (!StringUtils.hasLength(traceId)) {
traceId = TraceContext.traceId();
}
// 未插入探针的情况 或skyWalking未运行的情况
if (!StringUtils.hasLength(traceId) || ERROR_STR.contains(traceId)) {
traceId = IdGeneratorUtils.getIdStr();
}
response.setHeader(TRACE_ID_HEADER, traceId);
// 放入日志MDC
MDC.put("tid", traceId);
// 放入本地线程
clusterTrace.setTraceId(traceId);
LOGGER.info("Trace-Id:{},PATH:{}", traceId, request.getRequestURI());
return true;
}
@Override
public void afterCompletion(
HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex)
throws Exception {
MDC.remove("tid");
clusterTrace.removeTraceId();
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy