Core instrumentation library for the Prometheus Java client, providing fundamental metric types for application monitoring
npx @tessl/cli install tessl/maven-io-prometheus--simpleclient@0.16.00
# Prometheus Java Client - Simple Client
1
2
The Prometheus Java simpleclient library provides the core instrumentation classes for monitoring Java applications. It offers fundamental metric types (Counter, Gauge, Histogram, Summary, Info, Enumeration) for application metrics, with support for labels, exemplars, and thread-safe operations. The library is designed with zero runtime dependencies and provides standardized ways to instrument code, collect metrics, and expose them for scraping by Prometheus servers.
3
4
## Package Information
5
6
- **Package Name**: io.prometheus:simpleclient
7
- **Package Type**: maven
8
- **Language**: Java
9
- **Installation**: Add to your Maven `pom.xml`:
10
11
```xml
12
<dependency>
13
<groupId>io.prometheus</groupId>
14
<artifactId>simpleclient</artifactId>
15
<version>0.16.0</version>
16
</dependency>
17
```
18
19
For Gradle:
20
21
```gradle
22
implementation 'io.prometheus:simpleclient:0.16.0'
23
```
24
25
## Core Imports
26
27
```java
28
import io.prometheus.client.*;
29
```
30
31
For specific metric types:
32
33
```java
34
import io.prometheus.client.Counter;
35
import io.prometheus.client.Gauge;
36
import io.prometheus.client.Histogram;
37
import io.prometheus.client.Summary;
38
import io.prometheus.client.Info;
39
import io.prometheus.client.Enumeration;
40
import io.prometheus.client.CollectorRegistry;
41
```
42
43
## Basic Usage
44
45
```java
46
import io.prometheus.client.Counter;
47
import io.prometheus.client.Gauge;
48
import io.prometheus.client.Histogram;
49
50
public class Example {
51
// Counter for tracking total requests
52
static final Counter requestsTotal = Counter.build()
53
.name("requests_total")
54
.help("Total requests")
55
.register();
56
57
// Gauge for current in-progress requests
58
static final Gauge inProgressRequests = Gauge.build()
59
.name("inprogress_requests")
60
.help("Requests in progress")
61
.register();
62
63
// Histogram for request duration tracking
64
static final Histogram requestDuration = Histogram.build()
65
.name("request_duration_seconds")
66
.help("Request duration in seconds")
67
.register();
68
69
public void handleRequest() {
70
requestsTotal.inc();
71
inProgressRequests.inc();
72
73
Histogram.Timer timer = requestDuration.startTimer();
74
try {
75
// Handle request logic here
76
} finally {
77
timer.observeDuration();
78
inProgressRequests.dec();
79
}
80
}
81
}
82
```
83
84
## Architecture
85
86
The Prometheus Java client is built around several key components:
87
88
- **Metric Types**: Counter, Gauge, Histogram, Summary, Info, and Enumeration provide different measurement patterns
89
- **Registry System**: CollectorRegistry manages metric collection and export
90
- **Label Support**: Multi-dimensional metrics with label-based children
91
- **Builder Pattern**: Fluent configuration API for all metric types
92
- **Thread Safety**: All operations are thread-safe for concurrent use
93
- **Exemplar Integration**: Support for linking metrics to distributed traces
94
95
## Capabilities
96
97
### Counter Metrics
98
99
Counter metrics track counts and totals that only increase (except on resets). Perfect for tracking requests, errors, completed tasks, and cumulative values.
100
101
```java { .api }
102
public class Counter extends SimpleCollector<Counter.Child> {
103
public static Counter.Builder build();
104
public static Counter.Builder build(String name, String help);
105
public void inc();
106
public void inc(double amt);
107
public void incWithExemplar(String... exemplarLabels);
108
public void incWithExemplar(double amt, String... exemplarLabels);
109
public double get();
110
}
111
```
112
113
[Counter Metrics](./counter.md)
114
115
### Gauge Metrics
116
117
Gauge metrics track values that can go up and down, like memory usage, queue sizes, temperature, or active connections.
118
119
```java { .api }
120
public class Gauge extends SimpleCollector<Gauge.Child> {
121
public static Gauge.Builder build();
122
public static Gauge.Builder build(String name, String help);
123
public void inc();
124
public void inc(double amt);
125
public void dec();
126
public void dec(double amt);
127
public void set(double val);
128
public void setToCurrentTime();
129
public Timer startTimer();
130
public double get();
131
}
132
```
133
134
[Gauge Metrics](./gauge.md)
135
136
### Histogram Metrics
137
138
Histogram metrics track distributions of values like request latencies or response sizes, organizing observations into configurable buckets.
139
140
```java { .api }
141
public class Histogram extends SimpleCollector<Histogram.Child> {
142
public static Histogram.Builder build();
143
public static Histogram.Builder build(String name, String help);
144
public void observe(double amt);
145
public void observeWithExemplar(double amt, String... exemplarLabels);
146
public Timer startTimer();
147
public double time(Runnable timeable);
148
public <E> E time(Callable<E> timeable);
149
}
150
```
151
152
[Histogram Metrics](./histogram.md)
153
154
### Summary Metrics
155
156
Summary metrics track quantiles and distributions with configurable sliding time windows and precise quantile calculations.
157
158
```java { .api }
159
public class Summary extends SimpleCollector<Summary.Child> {
160
public static Summary.Builder build();
161
public static Summary.Builder build(String name, String help);
162
public void observe(double amt);
163
public Timer startTimer();
164
public double time(Runnable timeable);
165
public <E> E time(Callable<E> timeable);
166
}
167
```
168
169
[Summary Metrics](./summary.md)
170
171
### Info Metrics
172
173
Info metrics provide key-value metadata pairs for build information, version details, and configuration data.
174
175
```java { .api }
176
public class Info extends SimpleCollector<Info.Child> {
177
public static Info.Builder build();
178
public static Info.Builder build(String name, String help);
179
public void info(String... labelPairs);
180
}
181
```
182
183
[Info Metrics](./info.md)
184
185
### Enumeration Metrics
186
187
Enumeration metrics track which of a set of states something is in, perfect for status tracking and state machines.
188
189
```java { .api }
190
public class Enumeration extends SimpleCollector<Enumeration.Child> {
191
public static Enumeration.Builder build();
192
public static Enumeration.Builder build(String name, String help);
193
public void state(String state);
194
public void state(Enum<?> state);
195
}
196
```
197
198
[Enumeration Metrics](./enumeration.md)
199
200
### Registry Management
201
202
The CollectorRegistry manages metric registration, collection, and provides access to metric samples for export.
203
204
```java { .api }
205
public class CollectorRegistry {
206
public static final CollectorRegistry defaultRegistry;
207
public void register(Collector m);
208
public void unregister(Collector m);
209
public void clear();
210
public Enumeration<MetricFamilySamples> metricFamilySamples();
211
public Double getSampleValue(String name);
212
}
213
```
214
215
[Registry Management](./registry.md)
216
217
### Exemplar Support
218
219
Exemplars link individual metric observations to distributed trace data, enabling correlation between metrics and traces.
220
221
```java { .api }
222
public class Exemplar {
223
public Exemplar(double value, String... labels);
224
public Exemplar(double value, Long timestampMs, String... labels);
225
public double getValue();
226
public Long getTimestampMs();
227
public String[] getLabels();
228
}
229
```
230
231
[Exemplar Support](./exemplars.md)
232
233
## Types
234
235
### Base Types
236
237
```java { .api }
238
public abstract class Collector {
239
/** Nanoseconds per second constant for time conversions */
240
public static final double NANOSECONDS_PER_SECOND = 1E9;
241
242
/** Milliseconds per second constant for time conversions */
243
public static final double MILLISECONDS_PER_SECOND = 1E3;
244
245
/**
246
* Collect all metric samples from this collector
247
* @return List of MetricFamilySamples
248
*/
249
public abstract List<MetricFamilySamples> collect();
250
251
/**
252
* Collect filtered metric samples from this collector
253
* @param sampleNameFilter Predicate to filter sample names
254
* @return List of filtered MetricFamilySamples
255
*/
256
public List<MetricFamilySamples> collect(Predicate<String> sampleNameFilter);
257
258
/**
259
* Register this collector with the default registry
260
* @return This collector for method chaining
261
*/
262
public <T extends Collector> T register();
263
264
/**
265
* Register this collector with specified registry
266
* @param registry Registry to register with
267
* @return This collector for method chaining
268
*/
269
public <T extends Collector> T register(CollectorRegistry registry);
270
271
/**
272
* Sanitize metric name for Prometheus compatibility
273
* @param metricName Raw metric name
274
* @return Sanitized metric name
275
*/
276
public static String sanitizeMetricName(String metricName);
277
278
/**
279
* Convert double to Prometheus Go-style string
280
* @param d Double value to convert
281
* @return String representation
282
*/
283
public static String doubleToGoString(double d);
284
285
public enum Type {
286
UNKNOWN, COUNTER, GAUGE, STATE_SET, INFO, HISTOGRAM, GAUGE_HISTOGRAM, SUMMARY
287
}
288
289
/**
290
* Interface for collectors that provide metric descriptions
291
*/
292
public interface Describable {
293
/**
294
* Describe the metrics this collector exposes
295
* @return List of MetricFamilySamples for metric descriptions
296
*/
297
List<MetricFamilySamples> describe();
298
}
299
}
300
301
public abstract class SimpleCollector<Child> extends Collector {
302
/** Full metric name including namespace and subsystem */
303
protected final String fullname;
304
305
/** Help text for this metric */
306
protected final String help;
307
308
/** Unit for this metric */
309
protected final String unit;
310
311
/** Label names for this metric */
312
protected final List<String> labelNames;
313
314
/**
315
* Get child instance for specific label values
316
* @param labelValues Values for each defined label name
317
* @return Child instance for these label values
318
*/
319
public Child labels(String... labelValues);
320
321
/**
322
* Remove child for specific label values
323
* @param labelValues Values identifying child to remove
324
*/
325
public void remove(String... labelValues);
326
327
/**
328
* Remove all children
329
*/
330
public void clear();
331
332
/**
333
* Set child instance for specific label values
334
* @param child Child instance to set
335
* @param labelValues Label values for this child
336
* @return This collector for method chaining
337
*/
338
public <T extends Collector> T setChild(Child child, String... labelValues);
339
340
/**
341
* Create new child instance - implemented by subclasses
342
* @return New child instance
343
*/
344
protected abstract Child newChild();
345
}
346
347
public interface Predicate<T> {
348
/**
349
* Test if input matches this predicate
350
* @param t Input value to test
351
* @return true if input matches predicate
352
*/
353
boolean test(T t);
354
}
355
```
356
357
### Builder Pattern Types
358
359
```java { .api }
360
public abstract static class Builder<B extends Builder<B, C>, C> {
361
public B name(String name);
362
public B help(String help);
363
public B labelNames(String... labelNames);
364
public B namespace(String namespace);
365
public B subsystem(String subsystem);
366
public B unit(String unit);
367
public C register();
368
public C register(CollectorRegistry registry);
369
public abstract C create();
370
}
371
```
372
373
### Simple Timer Utility
374
375
Utility class for precise duration measurement in seconds without direct metric registration.
376
377
```java { .api }
378
public class SimpleTimer {
379
/**
380
* Create a new SimpleTimer starting at current time
381
*/
382
public SimpleTimer();
383
384
/**
385
* Get elapsed time since timer creation
386
* @return Duration in seconds as double
387
*/
388
public double elapsedSeconds();
389
390
/**
391
* Calculate elapsed seconds from nanosecond timestamps
392
* @param startNanos Start time in nanoseconds
393
* @param endNanos End time in nanoseconds
394
* @return Duration in seconds
395
*/
396
public static double elapsedSecondsFromNanos(long startNanos, long endNanos);
397
}
398
```
399
400
### Sample and Family Types
401
402
```java { .api }
403
public static class MetricFamilySamples {
404
public final String name;
405
public final String unit;
406
public final Type type;
407
public final String help;
408
public final List<Sample> samples;
409
410
/**
411
* Filter samples by predicate
412
* @param sampleNameFilter Predicate to test sample names
413
* @return Filtered MetricFamilySamples or null if no matches
414
*/
415
public MetricFamilySamples filter(Predicate<String> sampleNameFilter);
416
417
/**
418
* Get all reserved sample names for this metric family
419
* @return Array of reserved sample names
420
*/
421
public String[] getNames();
422
423
public static class Sample {
424
public final String name;
425
public final List<String> labelNames;
426
public final List<String> labelValues;
427
public final double value;
428
public final Exemplar exemplar;
429
public final Long timestampMs;
430
}
431
}
432
```
433
434
### MetricFamily Helper Classes
435
436
For custom collectors and advanced use cases.
437
438
```java { .api }
439
public class CounterMetricFamily extends Collector.MetricFamilySamples {
440
/**
441
* Create counter metric family without labels
442
* @param name Metric name (without _total suffix)
443
* @param help Help text
444
* @param value Counter value
445
*/
446
public CounterMetricFamily(String name, String help, double value);
447
448
/**
449
* Create counter metric family with labels
450
* @param name Metric name (without _total suffix)
451
* @param help Help text
452
* @param labelNames List of label names
453
*/
454
public CounterMetricFamily(String name, String help, List<String> labelNames);
455
456
/**
457
* Add metric sample with label values
458
* @param labelValues Values for each label
459
* @param value Counter value
460
* @return This instance for method chaining
461
*/
462
public CounterMetricFamily addMetric(List<String> labelValues, double value);
463
}
464
465
public class GaugeMetricFamily extends Collector.MetricFamilySamples {
466
public GaugeMetricFamily(String name, String help, double value);
467
public GaugeMetricFamily(String name, String help, List<String> labelNames);
468
public GaugeMetricFamily addMetric(List<String> labelValues, double value);
469
}
470
471
public class SummaryMetricFamily extends Collector.MetricFamilySamples {
472
public SummaryMetricFamily(String name, String help, double count, double sum);
473
public SummaryMetricFamily(String name, String help, List<String> labelNames);
474
public SummaryMetricFamily addMetric(List<String> labelValues, double count, double sum);
475
public SummaryMetricFamily addMetric(List<String> labelValues, double count, double sum, List<Double> quantiles);
476
}
477
```
478
479
### Utility Interfaces
480
481
```java { .api }
482
public interface Predicate<T> {
483
/**
484
* Test if the given input matches this predicate
485
* @param t Input to test
486
* @return true if input matches predicate
487
*/
488
boolean test(T t);
489
}
490
491
public class SampleNameFilter {
492
/**
493
* Static utility methods for creating sample name filters
494
*/
495
}
496
```