Add a custom field in a Prometheus default metrics endpoint (actuator/prometheus) , using Spring Cloud Gateway

65 views Asked by At

I'm using Prometheus endpoint for monitoring in my Spring Cloug Gateway project , when call /actuator/prometheus , I have different metrics like : spring_cloud_gateway_requests_seconds_count{httpMethod="POST",httpStatusCode="403",outcome="CLIENT_ERROR",routeId="JIBackendRESTCall",routeUri="https://run.mocky.io:443/v3/78722176-fd22-4e94-bd49-9faf07240df3",status="FORBIDDEN",} 2.0

I want to add some new fields in this specific named metrics , like "... , status="FORBIDDEN, clientId="123", newString = "HI" } 2.0" How can I do this in a chains of filter with a GatewayFilter? Other filters in chains works fine , I need only to implement this new one , that should let me to modify existing metrics. I'm using java 11.

I've try something like this ,but doesn't work

Thanks.

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class CustomFilter extends AbstractGatewayFilterFactory<CustomFilter.Config> {

    public CustomFilter() {
        super(Config.class);
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            
            return exchange.getRequest().getBody()
                    .map(dataBuffer -> {
                        byte[] bytes = new byte[dataBuffer.readableByteCount()];
                        dataBuffer.read(bytes);
                        
                        String metrics = new String(bytes);
                        
                        
                        String modifiedMetrics = addFieldToMetrics(metrics, "TagName", "TagValue");
                        
                        
                        exchange.getRequest().mutate().body(modifiedMetrics.getBytes());
                        return exchange;
                    })
                    .flatMap(chain::filter);
        };
    }

    private String addFieldToMetrics(String metrics, String fieldName, String fieldValue) {
       
        return metrics.replace(
                "spring_cloud_gateway_requests_seconds_count",
                "spring_cloud_gateway_requests_seconds_count{" + fieldName + "=\"" + fieldValue + "\""
        );
    }

    public static class Config {
        
    }
}

0

There are 0 answers