From a9ebd34e213558fa2d426517c4a1c6e9bbcf372b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=86=A1=EC=98=81=EB=AF=BC?= Date: Mon, 1 Jul 2024 16:49:49 +0900 Subject: [PATCH] feat: add logging filter --- .../gateway/filter/APIGatewayLogger.java | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 api-gateway/src/main/java/kr/mafoo/gateway/filter/APIGatewayLogger.java diff --git a/api-gateway/src/main/java/kr/mafoo/gateway/filter/APIGatewayLogger.java b/api-gateway/src/main/java/kr/mafoo/gateway/filter/APIGatewayLogger.java new file mode 100644 index 0000000..66d9ab9 --- /dev/null +++ b/api-gateway/src/main/java/kr/mafoo/gateway/filter/APIGatewayLogger.java @@ -0,0 +1,38 @@ +package kr.mafoo.gateway.filter; + +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.http.server.reactive.ServerHttpRequest; +import org.springframework.http.server.reactive.ServerHttpResponse; +import org.springframework.stereotype.Component; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; + +import java.net.InetSocketAddress; + +@Component +public class APIGatewayLogger implements GlobalFilter { + private final Logger logger = LoggerFactory.getLogger(APIGatewayLogger.class); + + @Override + public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { + long startTime = System.currentTimeMillis(); + ServerHttpRequest request = exchange.getRequest(); + ServerHttpResponse response = exchange.getResponse(); + + String userAgent = request.getHeaders().getFirst("User-Agent"); + String proxyIp = request.getHeaders().getFirst("X-Forwarded-For"); + InetSocketAddress address = request.getRemoteAddress(); + String originIp = proxyIp != null ? proxyIp : (address != null ? address.toString() : "UNKNOWN SOURCE"); + String fullPath = request.getURI().getPath() + (request.getURI().getQuery() != null ? "?" + request.getURI().getQuery() : ""); + return chain + .filter(exchange) + .doOnSuccess(resVoid -> { + long executionTime = System.currentTimeMillis() - startTime; + logger.info("{} {} {} {} {}ms {}", request.getMethod(), fullPath, originIp, + response.getStatusCode(), executionTime, userAgent); + }); + } +}