|
@@ -1,6 +1,7 @@
|
|
|
package cn.hfln.framework.gateway.componet;
|
|
|
|
|
|
import lombok.extern.slf4j.Slf4j;
|
|
|
+import org.slf4j.MDC;
|
|
|
import org.springframework.core.Ordered;
|
|
|
import org.springframework.core.annotation.Order;
|
|
|
import org.springframework.http.server.reactive.ServerHttpRequest;
|
|
@@ -10,6 +11,8 @@ import org.springframework.web.server.WebFilter;
|
|
|
import org.springframework.web.server.WebFilterChain;
|
|
|
import reactor.core.publisher.Mono;
|
|
|
|
|
|
+import java.util.UUID;
|
|
|
+
|
|
|
@Component
|
|
|
@Slf4j
|
|
|
@Order(Ordered.HIGHEST_PRECEDENCE)
|
|
@@ -18,11 +21,18 @@ public class GatewayLogFilter implements WebFilter, Ordered {
|
|
|
@Override
|
|
|
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
|
|
|
ServerHttpRequest request = exchange.getRequest();
|
|
|
-
|
|
|
- // 打印请求日志(转发前)
|
|
|
+
|
|
|
+ // 生成或获取追踪 ID(例如使用 UUID)
|
|
|
+ String traceId = UUID.randomUUID().toString().replace("-", "");
|
|
|
+ // 将追踪 ID 添加到请求头
|
|
|
+ ServerHttpRequest mutatedRequest = request.mutate()
|
|
|
+ .header("X-Trace-Id", traceId)
|
|
|
+ .build();
|
|
|
+ MDC.put("X-Trace-Id", traceId);
|
|
|
+ // 打印带追踪 ID 的请求日志
|
|
|
long start = System.currentTimeMillis();
|
|
|
log.info("[Gateway] Request => Method: {}, Path: {}",
|
|
|
- request.getMethod(),
|
|
|
+ request.getMethod(),
|
|
|
request.getPath());
|
|
|
|
|
|
return chain.filter(exchange).then(Mono.fromRunnable(() -> {
|
|
@@ -30,6 +40,7 @@ public class GatewayLogFilter implements WebFilter, Ordered {
|
|
|
log.info("[Gateway] Response => Status: {}, cost: {}ms",
|
|
|
exchange.getResponse().getStatusCode(),
|
|
|
System.currentTimeMillis() - start);
|
|
|
+ MDC.remove("X-Trace-Id");
|
|
|
}));
|
|
|
}
|
|
|
|