Spring Cloud之Gateway请求日志记录(请求和响应报文)
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets;
public class RequestResponseLoggingFilter implements GlobalFilter {
private Logger logger = LoggerFactory.getLogger(RequestResponseLoggingFilter.class);
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
logger.info("Request Method: {} URL: {}", request.getMethodValue(), request.getURI());
// 日志请求数据
logRequest(request);
// 记录响应数据
return chain.filter(exchange).then(
Mono.fromRunnable(() -> {
ServerHttpResponse response = exchange.getResponse();
// 日志响应数据
logResponse(response);
})
);
}
private void logRequest(ServerHttpRequest request) {
// 打印请求体
request.getBody().subscribe(buffer -> {
String body = new String(buffer.asByteBuffer().array(), StandardCharsets.UTF_8);
logger.info("Request Body: {}", body);
});
}
private void logResponse(ServerHttpResponse response) {
// 打印响应体
DataBufferUtils.join(response.getBody())
.subscribe(buffer -> {
byte[] bytes = new byte[buffer.readableByteCount()];
buffer.read(bytes);
String body = new String(bytes, StandardCharsets.UTF_8);
logger.info("Response Body: {}", body);
});
}
}
这段代码实现了一个简单的全局过滤器,用于记录Spring Cloud Gateway中的请求和响应日志。它首先记录请求方法和URL,然后记录请求体,最后在响应完成后记录响应体。这对于调试和监控API网关的流量非常有用。
评论已关闭