Prometheus Integration - Java Client Part 2

Prometheus Integration - Java Client Part 2

There were some issue while processing the HttpServeletRequest while pushing metrics to prometheus another alternative could be using the ContainerRequestFilter.

If you need to process the url fetch the query params the ContainerRequestFilter might be easy and more helpful.

Example Metrics filter with ContainerRequestFilter:

// Use case to fetch header
String key = requestContext.getHeaderString("key");
// Fetch the URI path :
 String path = requestContext.getUriInfo().getPath();
 // Fetch the path params: 
 MultivaluedMap<String, String> pathParams = requestContext.getUriInfo().getPathParameters();

Sample methods :

 @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        // Method called before the request
    }
    
    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
            throws IOException {
     // post processor
    }

Pushing metrics with historgram :
Histogram.Builder builder = Histogram.build().labelNames("path", "method", "address");
histogram = builder.help("To track API Calls").name(metricName).register();
Histogram.Timer timer = histogram.labels(path, request.getMethod(), request.getRemoteAddr()).startTimer();
timer.observeDuration();
Note :

  1. While pushing metrics to prometheus if there is a - in the metrics name this could cause issues while pushing metrics hence ensure to replace it with a "_"
  2. Pushing path parameters to Prometheus isn't a good idea.  The below code could help remove the path parameter value and replace it with key.

MultivaluedMap<String, String> pathParams = requestContext.getUriInfo().getPathParameters();
    for (Entry<String, List<String>> query : pathParams.entrySet()) {
        String key = query.getKey();
        List<String> values = query.getValue();
        for (String value : values) {
            pathToPush = pathToPush.replace(value, key);
        }
    }

Comments