springcloud-gateway中基本的请求日志打印

  • 定义一个业务的过滤器
public class AuthFilter implements GlobalFilter, Ordered {
    private static final Logger log = LoggerFactory.getLogger(AuthFilter.class);





    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
exchange.getAttributes().put("start_time",System.currentTimeMillis());
....

    @Override
    public int getOrder() {
        return NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER-2;
    }

  • 定义一个日志过滤器
Route route =(Route) exchange.getAttributes().get(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
        //路由ID
        String routeId = route.getId();
        Long startTime = exchange.getAttribute("start_time");
        //获取耗时时长
        final long duration = System.currentTimeMillis() - (Objects.isNull(startTime)?0L:startTime);
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //请求路径
        String requestUri = request.getURI().getPath();
        //请求方法
        String method = request.getMethodValue();
        //请求的url参数
        String param = MapUtil.join(request.getQueryParams(), "&", "=");
        //响应码
        int respStatusCode= Objects.requireNonNull(response.getStatusCode()).value();
        //respStatusCode|Method|Host|Path|Query|Time|server_id
        log.info("{}|{}|{}|{}|{}|{}ms|{}",respStatusCode,method, request.getURI().getHost(),
                requestUri,param,duration,routeId);
        return chain.filter(exchange.mutate().request(request).build());
    }

    @Override
    public int getOrder() {
        return NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER-1;
    }
  • 打印样例

springcloud-gateway中基本的请求日志打印

上一篇:java搭建直播商城 微服务商城 百万千万级商城 分布式商城 VR全景商城 saas商城 b2b2c商城 o2o商城 积分商城 秒杀商城 拼团商城 分销商城


下一篇:prometheus operator告警规则(一):你的cpu够用吗?