1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| import lombok.extern.slf4j.Slf4j; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.GlobalFilter; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.DataBufferUtils; import org.springframework.http.HttpMethod; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.http.server.reactive.ServerHttpRequestDecorator; import org.springframework.stereotype.Component; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.stream.Collectors;
@Slf4j @Component public class LoggerFilter implements GlobalFilter {
@Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { ServerHttpRequest request = exchange.getRequest(); String method = request.getMethodValue();
if (HttpMethod.POST.matches(method)) { return DataBufferUtils.join(exchange.getRequest().getBody()) .flatMap(dataBuffer -> { byte[] bytes = new byte[dataBuffer.readableByteCount()]; dataBuffer.read(bytes); String bodyString = new String(bytes, StandardCharsets.UTF_8); logtrace(exchange, bodyString); exchange.getAttributes().put("POST_BODY", bodyString); DataBufferUtils.release(dataBuffer); Flux<DataBuffer> cachedFlux = Flux.defer(() -> { DataBuffer buffer = exchange.getResponse().bufferFactory() .wrap(bytes); return Mono.just(buffer); });
ServerHttpRequest mutatedRequest = new ServerHttpRequestDecorator( exchange.getRequest()) { @Override public Flux<DataBuffer> getBody() { return cachedFlux; } }; return chain.filter(exchange.mutate().request(mutatedRequest) .build()); }); } else if (HttpMethod.GET.matches(method)) { Map m = request.getQueryParams(); logtrace(exchange, m.toString()); } return chain.filter(exchange); }
private void logtrace(ServerWebExchange exchange, String param) { ServerHttpRequest serverHttpRequest = exchange.getRequest(); String path = serverHttpRequest.getURI().getPath(); String method = serverHttpRequest.getMethodValue(); String headers = serverHttpRequest.getHeaders().entrySet() .stream() .map(entry -> " " + entry.getKey() + ": [" + String.join(";", entry.getValue()) + "]") .collect(Collectors.joining("\n")); log.info("\n" + "---------------- ---------------- ---------------->>\n" + "HttpMethod : {}\n" + "Uri : {}\n" + "Param : {}\n" + "Headers : \n" + "{}\n" + "\"<<---------------- ---------------- ----------------" , method, path, param, headers); }
}
|