@@ -30,29 +30,65 @@ class BooleanMetric @JvmOverloads constructor(
30
30
/* * the namespace (prefix) of this metric */
31
31
namespace : String ,
32
32
/* * an optional initial value for this metric */
33
- internal val initialValue : Boolean = false
33
+ internal val initialValue : Boolean = false ,
34
+ /* * Label names for this metric. If non-empty, the initial value must be false and all get/update calls MUST
35
+ * specify values for the labels. Calls to simply get() or set() will fail with an exception. */
36
+ val labelNames : List <String > = emptyList()
34
37
) : Metric<Boolean>() {
35
- private val gauge =
36
- Gauge .build(name, help).namespace(namespace).create().apply { set(if (initialValue) 1.0 else 0.0 ) }
38
+ private val gauge = run {
39
+ val builder = Gauge .build(name, help).namespace(namespace)
40
+ if (labelNames.isNotEmpty()) {
41
+ builder.labelNames(* labelNames.toTypedArray())
42
+ if (initialValue) {
43
+ throw IllegalArgumentException (" Cannot set an initial value for a labeled gauge" )
44
+ }
45
+ }
46
+ builder.create().apply {
47
+ if (initialValue) {
48
+ set(1.0 )
49
+ }
50
+ }
51
+ }
37
52
53
+ override val supportsJson: Boolean = labelNames.isEmpty()
38
54
override fun get () = gauge.get() != 0.0
55
+ fun get (labels : List <String >) = gauge.labels(* labels.toTypedArray()).get() != 0.0
39
56
40
- override fun reset () = set(initialValue)
57
+ override fun reset () = synchronized(gauge) {
58
+ gauge.clear()
59
+ if (initialValue) {
60
+ gauge.set(1.0 )
61
+ }
62
+ }
41
63
42
64
override fun register (registry : CollectorRegistry ) = this .also { registry.register(gauge) }
43
65
44
66
/* *
45
67
* Atomically sets the gauge to the given value.
46
68
*/
47
- fun set (newValue : Boolean ): Unit = synchronized(gauge) { gauge.set(if (newValue) 1.0 else 0.0 ) }
69
+ fun set (newValue : Boolean , labels : List <String > = emptyList()): Unit = synchronized(gauge) {
70
+ if (labels.isEmpty()) {
71
+ gauge.set(if (newValue) 1.0 else 0.0 )
72
+ } else {
73
+ gauge.labels(* labels.toTypedArray()).set(if (newValue) 1.0 else 0.0 )
74
+ }
75
+ }
48
76
49
77
/* *
50
78
* Atomically sets the gauge to the given value, returning the updated value.
51
79
*
52
80
* @return the updated value
53
81
*/
54
- fun setAndGet (newValue : Boolean ): Boolean = synchronized(gauge) {
55
- gauge. set(if ( newValue) 1.0 else 0.0 )
82
+ fun setAndGet (newValue : Boolean , labels : List < String > = emptyList() ): Boolean = synchronized(gauge) {
83
+ set(newValue, labels )
56
84
return newValue
57
85
}
86
+
87
+ /* * Remove the child with the given labels (the metric with those labels will stop being emitted) */
88
+ fun remove (labels : List <String > = emptyList()) = synchronized(gauge) {
89
+ if (labels.isNotEmpty()) {
90
+ gauge.remove(* labels.toTypedArray())
91
+ }
92
+ }
93
+ internal fun collect () = gauge.collect()
58
94
}
0 commit comments