CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-io-prometheus--simpleclient

Core instrumentation library for the Prometheus Java client, providing fundamental metric types for application monitoring

Pending
Overview
Eval results
Files

gauge.mddocs/

Gauge Metrics

Gauge metrics track values that can go up and down, representing instantaneous measurements like memory usage, queue sizes, temperature, active connections, or any value that fluctuates over time.

Capabilities

Gauge Creation

Create gauge metrics using the builder pattern with required name and help text.

/**
 * Create a new Gauge builder
 * @return Builder instance for configuration
 */
public static Gauge.Builder build();

/**
 * Create a new Gauge builder with required fields
 * @param name The metric name
 * @param help The help text describing the metric
 * @return Builder instance for configuration
 */
public static Gauge.Builder build(String name, String help);

Usage Example:

import io.prometheus.client.Gauge;

// Basic gauge
Gauge memoryUsage = Gauge.build()
    .name("memory_usage_bytes")
    .help("Current memory usage in bytes")
    .register();

// Gauge with labels
Gauge queueSize = Gauge.build()
    .name("queue_size")
    .help("Current queue size")
    .labelNames("queue_name", "priority")
    .register();

Gauge Builder Configuration

Configure gauge metrics with labels, namespace, and units.

public static class Builder extends SimpleCollector.Builder<Builder, Gauge> {
    // Inherits standard builder methods: name(), help(), labelNames(), 
    // namespace(), subsystem(), unit(), register(), create()
}

Basic Gauge Operations

Modify gauge values with increment, decrement, and set operations.

/**
 * Increment gauge by 1
 */
public void inc();

/**
 * Increment gauge by specified amount
 * @param amt Amount to increment (can be negative)
 */
public void inc(double amt);

/**
 * Decrement gauge by 1
 */
public void dec();

/**
 * Decrement gauge by specified amount
 * @param amt Amount to decrement (can be negative)
 */
public void dec(double amt);

/**
 * Set gauge to specific value
 * @param val New gauge value
 */
public void set(double val);

/**
 * Set gauge to current Unix timestamp
 */
public void setToCurrentTime();

/**
 * Get current gauge value
 * @return Current gauge value
 */
public double get();

Usage Examples:

// Basic operations
memoryUsage.set(1024 * 1024 * 512); // Set to 512MB
memoryUsage.inc(1024); // Add 1KB
memoryUsage.dec(512);  // Subtract 512 bytes

// Queue size tracking
queueSize.labels("tasks", "high").inc(); // Add item
queueSize.labels("tasks", "high").dec(); // Remove item
queueSize.labels("tasks", "low").set(10); // Set to 10

// Timestamp tracking
Gauge lastProcessed = Gauge.build()
    .name("last_processed_timestamp")
    .help("Last processing time")
    .register();
lastProcessed.setToCurrentTime();

Timer Operations

Use gauges for timing operations and duration measurements.

/**
 * Start a timer for duration measurement
 * @return Timer instance for duration tracking
 */
public Timer startTimer();

/**
 * Time a Runnable execution and set gauge to duration
 * @param timeable Code to time
 * @return Duration in seconds
 */
public double setToTime(Runnable timeable);

/**
 * Time a Callable execution and set gauge to duration
 * @param timeable Code to time
 * @return Result from callable
 * @throws RuntimeException if callable throws exception
 */
public <E> E setToTime(Callable<E> timeable);

Timer Class

Timer provides duration measurement capabilities for gauge metrics.

public static class Timer implements Closeable {
    /**
     * Set gauge to elapsed duration since timer start
     * @return Elapsed duration in seconds
     */
    public double setDuration();
    
    /**
     * Equivalent to setDuration() - implements Closeable
     */
    public void close();
}

Usage Examples:

// Manual timer usage
Gauge batchDuration = Gauge.build()
    .name("batch_processing_seconds")
    .help("Duration of batch processing")
    .register();

Gauge.Timer timer = batchDuration.startTimer();
try {
    // Batch processing logic
    processBatch();
} finally {
    timer.setDuration(); // Sets gauge to elapsed time
}

// Try-with-resources timer
try (Gauge.Timer timer = batchDuration.startTimer()) {
    processBatch(); // Automatically sets duration on close
}

// Lambda timing
double duration = batchDuration.setToTime(() -> {
    processBatch();
});

// Callable timing with return value
String result = batchDuration.setToTime(() -> {
    return processBatchWithResult();
});

Labeled Gauge Operations

Work with multi-dimensional gauges using label values to create distinct time series.

/**
 * Get gauge child for specific label values
 * @param labelValues Values for each label name (must match count)
 * @return Gauge.Child instance for the label combination
 * @throws IllegalArgumentException if wrong number of labels
 */
public Gauge.Child labels(String... labelValues);

/**
 * Remove gauge child for specific label values
 * @param labelValues Values identifying the child to remove
 */
public void remove(String... labelValues);

/**
 * Remove all gauge children
 */
public void clear();

Gauge Child Operations

Gauge.Child provides the same operations for labeled instances.

public static class Child {
    /** Increment child gauge by 1 */
    public void inc();
    
    /** Increment child gauge by amount */
    public void inc(double amt);
    
    /** Decrement child gauge by 1 */
    public void dec();
    
    /** Decrement child gauge by amount */
    public void dec(double amt);
    
    /** Set child gauge value */
    public void set(double val);
    
    /** Set child gauge to current timestamp */
    public void setToCurrentTime();
    
    /** Get current child gauge value */
    public double get();
    
    /** Start timer for child gauge */
    public Timer startTimer();
    
    /** Time runnable and set child gauge */
    public double setToTime(Runnable timeable);
    
    /** Time callable and set child gauge */
    public <E> E setToTime(Callable<E> timeable);
}

Usage Example:

// Connection pool monitoring
Gauge connectionPool = Gauge.build()
    .name("connection_pool_active")
    .help("Active connections in pool")
    .labelNames("database", "pool_type")
    .register();

// Track different pools
Gauge.Child mainDbPool = connectionPool.labels("main", "read_write");
Gauge.Child cachePool = connectionPool.labels("cache", "read_only");

// Update pool sizes
mainDbPool.set(25);
cachePool.inc(); // Add connection
cachePool.dec(); // Remove connection

// Time operations per pool
mainDbPool.setToTime(() -> executeQuery("SELECT * FROM users"));

Important Notes

Gauge Use Cases

Gauges are ideal for:

  • Resource Usage: Memory, CPU, disk space, network connections
  • Queue Sizes: Pending tasks, buffered items, backlog counts
  • Temperature/Health: System temperature, response times, error rates
  • Batch Progress: Items processed, completion percentage
  • Timestamps: Last update time, processing timestamps

Thread Safety

All gauge operations are thread-safe:

// Safe concurrent access
Gauge concurrentGauge = Gauge.build()
    .name("concurrent_value")
    .help("Thread-safe gauge")
    .register();

// Multiple threads can safely modify
concurrentGauge.inc(); // Thread 1
concurrentGauge.set(100); // Thread 2
concurrentGauge.dec(); // Thread 3

Performance Considerations

  • Gauge operations are lightweight and optimized for high-frequency updates
  • Use labels sparingly to avoid high cardinality issues
  • Timer operations use System.nanoTime() for precise measurements
  • Set operations are atomic and don't require synchronization

Common Patterns

// Resource monitoring
Gauge heapMemory = Gauge.build()
    .name("jvm_heap_memory_bytes")
    .help("JVM heap memory usage")
    .register();

// Update with runtime info
Runtime runtime = Runtime.getRuntime();
heapMemory.set(runtime.totalMemory() - runtime.freeMemory());

// Connection tracking with try-with-resources
Gauge activeConnections = Gauge.build()
    .name("db_connections_active")
    .help("Active database connections")
    .register();

public void executeWithConnection(Runnable task) {
    activeConnections.inc();
    try {
        task.run();
    } finally {
        activeConnections.dec();
    }
}

Install with Tessl CLI

npx tessl i tessl/maven-io-prometheus--simpleclient

docs

counter.md

enumeration.md

exemplars.md

gauge.md

histogram.md

index.md

info.md

registry.md

summary.md

tile.json