Spring Cloud Gateway打印請求的執行時間

具體需求:java

使用spring cloud gateway做爲網關,打印每一個請求的執行時長

具體實現:react

自定義GlobalFilter,當請求進入時記錄開始時間,當請求結束時,減去開始時間即爲具體的執行時長
package com.winture.gateway.filter;

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.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 打印請求參數及統計執行時長過濾器
 * @Version V1.0
 */
@Component
public class LoggingFilter implements GlobalFilter, Ordered {

    private static final Log logger = LogFactory.getLog(LoggingFilter.class);
    private static final String START_TIME = "startTime";

    public LoggingFilter() {
        logger.info("Loaded GlobalFilter [Logging]");
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String info = String.format("Method:{%s} Host:{%s} Path:{%s} Query:{%s}",
                exchange.getRequest().getMethod().name(),
                exchange.getRequest().getURI().getHost(),
                exchange.getRequest().getURI().getPath(),
                exchange.getRequest().getQueryParams());

        logger.info(info);

        exchange.getAttributes().put(START_TIME, System.currentTimeMillis());
        return chain.filter(exchange).then( Mono.fromRunnable(() -> {
            Long startTime = exchange.getAttribute(START_TIME);
            if (startTime != null) {
                Long executeTime = (System.currentTimeMillis() - startTime);
                logger.info(exchange.getRequest().getURI().getRawPath() + " : " + executeTime + "ms");
            }
        }));
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}

當網關啓動後,訪問網關,能夠看到以下的打印信息web

2018-08-31 18:35:02.644  INFO 14376 --- [ctor-http-nio-2] c.w.gateway.filter.LoggingFilter       : Method:{POST} Host:{127.0.0.1} Path:{/api/authorize} Query:{{}}
2018-08-31 18:35:02.678  INFO 14376 --- [ctor-http-nio-3] c.w.gateway.filter.LoggingFilter       : /api/authorize : 34ms
相關文章
相關標籤/搜索