Tuesday, 10 June 2025

How to expose Gauge metric using Prometheus Java Client?

In Prometheus, a Gauge is a type of metric used to represent a single numerical value that can go up and down.

 

Why Use Gauge?

·      You use Gauge when you want to knoe:

·      The current value of something (not how many times it happened)

·      Values that fluctuate

·      Tracking things like memory, temperature, CPU, queue size, etc.

 

Examples

·      How much memory is in use, it can go up or down based on load.

·      How much CPU the process is currently consuming.

·      How many HTTP requests are currently being handled, increases when a request comes in, decreases when it completes.

·      How many items are waiting to be processed, goes up when items come in, down when they’re handled.

·      Last event time, it shows the Unix timestamp (in seconds) when something last occurred.

 

In Java, using the Prometheus client library, you define a Gauge like this:

Gauge currentUsers = Gauge.build()
    .name("active_users_count")
    .help("Current number of active users in the app")
    .register();

Then you update it based on your logic:

currentUsers.set(10);         // set current value to 10
currentUsers.inc();           // increase by 1
currentUsers.dec();           // decrease by 1
currentUsers.inc(5);          // increase by 5
currentUsers.dec(2);          // decrease by 2

Find the below working application.

 

ActiveUserGaugeApp.java

package com.sample.app;

import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpExchange;
import io.prometheus.client.Gauge;
import io.prometheus.client.exporter.common.TextFormat;
import io.prometheus.client.CollectorRegistry;

import java.io.OutputStream;
import java.io.StringWriter;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Enumeration;

public class ActiveUserGaugeApp {

    // Gauge metric: can go up/down
    private static final Gauge activeUsersCount = Gauge.build()
            .name("active_users_count")
            .help("Current number of active users")
            .register();

    public static void main(String[] args) throws IOException {
        HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);

        // Endpoint to simulate user login (increase gauge)
        server.createContext("/login", exchange -> {
            activeUsersCount.inc();
            respond(exchange, "User logged in. Active users: " + activeUsersCount.get());
        });

        // Endpoint to simulate user logout (decrease gauge)
        server.createContext("/logout", exchange -> {
            activeUsersCount.dec();
            respond(exchange, "User logged out. Active users: " + activeUsersCount.get());
        });

        // Metrics endpoint
        server.createContext("/metrics", new MetricsHandler());

        server.setExecutor(null);
        server.start();
        System.out.println("Server started on http://localhost:8080");
        System.out.println("Try hitting /login and /logout, and check /metrics for updates.");
    }

    private static void respond(HttpExchange exchange, String message) throws IOException {
        exchange.sendResponseHeaders(200, message.length());
        OutputStream os = exchange.getResponseBody();
        os.write(message.getBytes());
        os.close();
    }

    // Handler to expose Prometheus metrics
    static class MetricsHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            StringWriter writer = new StringWriter();
            Enumeration<io.prometheus.client.Collector.MetricFamilySamples> samples =
                    CollectorRegistry.defaultRegistry.metricFamilySamples();
            TextFormat.write004(writer, samples);

            byte[] response = writer.toString().getBytes();
            exchange.getResponseHeaders().set("Content-Type", TextFormat.CONTENT_TYPE_004);
            exchange.sendResponseHeaders(200, response.length);
            try (OutputStream os = exchange.getResponseBody()) {
                os.write(response);
            }
        }
    }
}

Run the above application.

 

You will see following messages in the console.

 

Server started on http://localhost:8080

Try hitting /login and /logout, and check /metrics for updates.

 

Open the url ‘http://localhost:8080/metrics’ in browser, you can see active_users_count value as 0.

 


Hit http://localhost:8080/login endpoint twice, you can observe that the active_users_count is set to 2.0.

 


Hit ‘http://localhost:8080/logout’ endpoint, you can observe that active_users_count is set to 1.0  

 


In summary,

·      Gauge shows the current state or live value of something.

·      It’s ideal when values can both increase and decrease.

·      Great for monitoring resource usage, active sessions, queued items, and timestamps of events.

  

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment