Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SpringCloudGateway - Log incoming request url and corresponding route URI

I am new to spring cloud gateway, what I want is to log incoming request to corresponding route url, For e.g. if I have following route config:

      - id: route1
        uri: http://localhost:8585/
        predicates:
        - Path=/foo/**
        filters:
        - RewritePath=/foo/(?<segment>.*), /$\{segment}

Then for a incoming request of 'http://localhost:8080/foo/route1' following log message should be printed.

"Incoming request url 'http://localhost:8080/foo/route1' is routed to 'http://localhost:8585/route1'"

Is there any easy way of achieving this or can I achieve this just by setting log level.

Can you please help

like image 717
JavaCodeNet Avatar asked Jan 09 '19 19:01

JavaCodeNet


1 Answers

You could do it with a simple GlobalFilter.

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.Collections;
import java.util.Set;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR;

public class LoggingFilter implements GlobalFilter {
    Log log = LogFactory.getLog(getClass());

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        Set<URI> uris = exchange.getAttributeOrDefault(GATEWAY_ORIGINAL_REQUEST_URL_ATTR, Collections.emptySet());
        String originalUri = (uris.isEmpty()) ? "Unknown" : uris.iterator().next().toString();
        Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);
        URI routeUri = exchange.getAttribute(GATEWAY_REQUEST_URL_ATTR);
        log.info("Incoming request " + originalUri + " is routed to id: " + route.getId()
                + ", uri:" + routeUri);
        return chain.filter(exchange);
    }
}

produces the following in the logs.

2019-01-09 15:36:32.422  INFO 6870 --- [or-http-epoll-2] LoggingFilter                      : Incoming request http://localhost:8080/api/configserver/foo/default is routed to id: CompositeDiscoveryClient_CONFIGSERVER, uri:http://192.168.0.112:8888/foo/default
like image 167
spencergibb Avatar answered Oct 31 '22 02:10

spencergibb