or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

counter.mdenumeration.mdexemplars.mdgauge.mdhistogram.mdindex.mdinfo.mdregistry.mdsummary.md

gauge.mddocs/

0

# Gauge Metrics

1

2

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.

3

4

## Capabilities

5

6

### Gauge Creation

7

8

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

9

10

```java { .api }

11

/**

12

* Create a new Gauge builder

13

* @return Builder instance for configuration

14

*/

15

public static Gauge.Builder build();

16

17

/**

18

* Create a new Gauge builder with required fields

19

* @param name The metric name

20

* @param help The help text describing the metric

21

* @return Builder instance for configuration

22

*/

23

public static Gauge.Builder build(String name, String help);

24

```

25

26

**Usage Example:**

27

28

```java

29

import io.prometheus.client.Gauge;

30

31

// Basic gauge

32

Gauge memoryUsage = Gauge.build()

33

.name("memory_usage_bytes")

34

.help("Current memory usage in bytes")

35

.register();

36

37

// Gauge with labels

38

Gauge queueSize = Gauge.build()

39

.name("queue_size")

40

.help("Current queue size")

41

.labelNames("queue_name", "priority")

42

.register();

43

```

44

45

### Gauge Builder Configuration

46

47

Configure gauge metrics with labels, namespace, and units.

48

49

```java { .api }

50

public static class Builder extends SimpleCollector.Builder<Builder, Gauge> {

51

// Inherits standard builder methods: name(), help(), labelNames(),

52

// namespace(), subsystem(), unit(), register(), create()

53

}

54

```

55

56

### Basic Gauge Operations

57

58

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

59

60

```java { .api }

61

/**

62

* Increment gauge by 1

63

*/

64

public void inc();

65

66

/**

67

* Increment gauge by specified amount

68

* @param amt Amount to increment (can be negative)

69

*/

70

public void inc(double amt);

71

72

/**

73

* Decrement gauge by 1

74

*/

75

public void dec();

76

77

/**

78

* Decrement gauge by specified amount

79

* @param amt Amount to decrement (can be negative)

80

*/

81

public void dec(double amt);

82

83

/**

84

* Set gauge to specific value

85

* @param val New gauge value

86

*/

87

public void set(double val);

88

89

/**

90

* Set gauge to current Unix timestamp

91

*/

92

public void setToCurrentTime();

93

94

/**

95

* Get current gauge value

96

* @return Current gauge value

97

*/

98

public double get();

99

```

100

101

**Usage Examples:**

102

103

```java

104

// Basic operations

105

memoryUsage.set(1024 * 1024 * 512); // Set to 512MB

106

memoryUsage.inc(1024); // Add 1KB

107

memoryUsage.dec(512); // Subtract 512 bytes

108

109

// Queue size tracking

110

queueSize.labels("tasks", "high").inc(); // Add item

111

queueSize.labels("tasks", "high").dec(); // Remove item

112

queueSize.labels("tasks", "low").set(10); // Set to 10

113

114

// Timestamp tracking

115

Gauge lastProcessed = Gauge.build()

116

.name("last_processed_timestamp")

117

.help("Last processing time")

118

.register();

119

lastProcessed.setToCurrentTime();

120

```

121

122

### Timer Operations

123

124

Use gauges for timing operations and duration measurements.

125

126

```java { .api }

127

/**

128

* Start a timer for duration measurement

129

* @return Timer instance for duration tracking

130

*/

131

public Timer startTimer();

132

133

/**

134

* Time a Runnable execution and set gauge to duration

135

* @param timeable Code to time

136

* @return Duration in seconds

137

*/

138

public double setToTime(Runnable timeable);

139

140

/**

141

* Time a Callable execution and set gauge to duration

142

* @param timeable Code to time

143

* @return Result from callable

144

* @throws RuntimeException if callable throws exception

145

*/

146

public <E> E setToTime(Callable<E> timeable);

147

```

148

149

### Timer Class

150

151

Timer provides duration measurement capabilities for gauge metrics.

152

153

```java { .api }

154

public static class Timer implements Closeable {

155

/**

156

* Set gauge to elapsed duration since timer start

157

* @return Elapsed duration in seconds

158

*/

159

public double setDuration();

160

161

/**

162

* Equivalent to setDuration() - implements Closeable

163

*/

164

public void close();

165

}

166

```

167

168

**Usage Examples:**

169

170

```java

171

// Manual timer usage

172

Gauge batchDuration = Gauge.build()

173

.name("batch_processing_seconds")

174

.help("Duration of batch processing")

175

.register();

176

177

Gauge.Timer timer = batchDuration.startTimer();

178

try {

179

// Batch processing logic

180

processBatch();

181

} finally {

182

timer.setDuration(); // Sets gauge to elapsed time

183

}

184

185

// Try-with-resources timer

186

try (Gauge.Timer timer = batchDuration.startTimer()) {

187

processBatch(); // Automatically sets duration on close

188

}

189

190

// Lambda timing

191

double duration = batchDuration.setToTime(() -> {

192

processBatch();

193

});

194

195

// Callable timing with return value

196

String result = batchDuration.setToTime(() -> {

197

return processBatchWithResult();

198

});

199

```

200

201

### Labeled Gauge Operations

202

203

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

204

205

```java { .api }

206

/**

207

* Get gauge child for specific label values

208

* @param labelValues Values for each label name (must match count)

209

* @return Gauge.Child instance for the label combination

210

* @throws IllegalArgumentException if wrong number of labels

211

*/

212

public Gauge.Child labels(String... labelValues);

213

214

/**

215

* Remove gauge child for specific label values

216

* @param labelValues Values identifying the child to remove

217

*/

218

public void remove(String... labelValues);

219

220

/**

221

* Remove all gauge children

222

*/

223

public void clear();

224

```

225

226

### Gauge Child Operations

227

228

Gauge.Child provides the same operations for labeled instances.

229

230

```java { .api }

231

public static class Child {

232

/** Increment child gauge by 1 */

233

public void inc();

234

235

/** Increment child gauge by amount */

236

public void inc(double amt);

237

238

/** Decrement child gauge by 1 */

239

public void dec();

240

241

/** Decrement child gauge by amount */

242

public void dec(double amt);

243

244

/** Set child gauge value */

245

public void set(double val);

246

247

/** Set child gauge to current timestamp */

248

public void setToCurrentTime();

249

250

/** Get current child gauge value */

251

public double get();

252

253

/** Start timer for child gauge */

254

public Timer startTimer();

255

256

/** Time runnable and set child gauge */

257

public double setToTime(Runnable timeable);

258

259

/** Time callable and set child gauge */

260

public <E> E setToTime(Callable<E> timeable);

261

}

262

```

263

264

**Usage Example:**

265

266

```java

267

// Connection pool monitoring

268

Gauge connectionPool = Gauge.build()

269

.name("connection_pool_active")

270

.help("Active connections in pool")

271

.labelNames("database", "pool_type")

272

.register();

273

274

// Track different pools

275

Gauge.Child mainDbPool = connectionPool.labels("main", "read_write");

276

Gauge.Child cachePool = connectionPool.labels("cache", "read_only");

277

278

// Update pool sizes

279

mainDbPool.set(25);

280

cachePool.inc(); // Add connection

281

cachePool.dec(); // Remove connection

282

283

// Time operations per pool

284

mainDbPool.setToTime(() -> executeQuery("SELECT * FROM users"));

285

```

286

287

## Important Notes

288

289

### Gauge Use Cases

290

291

Gauges are ideal for:

292

- **Resource Usage**: Memory, CPU, disk space, network connections

293

- **Queue Sizes**: Pending tasks, buffered items, backlog counts

294

- **Temperature/Health**: System temperature, response times, error rates

295

- **Batch Progress**: Items processed, completion percentage

296

- **Timestamps**: Last update time, processing timestamps

297

298

### Thread Safety

299

300

All gauge operations are thread-safe:

301

302

```java

303

// Safe concurrent access

304

Gauge concurrentGauge = Gauge.build()

305

.name("concurrent_value")

306

.help("Thread-safe gauge")

307

.register();

308

309

// Multiple threads can safely modify

310

concurrentGauge.inc(); // Thread 1

311

concurrentGauge.set(100); // Thread 2

312

concurrentGauge.dec(); // Thread 3

313

```

314

315

### Performance Considerations

316

317

- Gauge operations are lightweight and optimized for high-frequency updates

318

- Use labels sparingly to avoid high cardinality issues

319

- Timer operations use `System.nanoTime()` for precise measurements

320

- Set operations are atomic and don't require synchronization

321

322

### Common Patterns

323

324

```java

325

// Resource monitoring

326

Gauge heapMemory = Gauge.build()

327

.name("jvm_heap_memory_bytes")

328

.help("JVM heap memory usage")

329

.register();

330

331

// Update with runtime info

332

Runtime runtime = Runtime.getRuntime();

333

heapMemory.set(runtime.totalMemory() - runtime.freeMemory());

334

335

// Connection tracking with try-with-resources

336

Gauge activeConnections = Gauge.build()

337

.name("db_connections_active")

338

.help("Active database connections")

339

.register();

340

341

public void executeWithConnection(Runnable task) {

342

activeConnections.inc();

343

try {

344

task.run();

345

} finally {

346

activeConnections.dec();

347

}

348

}

349

```