@@ -30,29 +30,65 @@ class BooleanMetric @JvmOverloads constructor(
3030 /* * the namespace (prefix) of this metric */
3131 namespace : String ,
3232 /* * 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()
3437) : 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+ }
3752
53+ override val supportsJson: Boolean = labelNames.isEmpty()
3854 override fun get () = gauge.get() != 0.0
55+ fun get (labels : List <String >) = gauge.labels(* labels.toTypedArray()).get() != 0.0
3956
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+ }
4163
4264 override fun register (registry : CollectorRegistry ) = this .also { registry.register(gauge) }
4365
4466 /* *
4567 * Atomically sets the gauge to the given value.
4668 */
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+ }
4876
4977 /* *
5078 * Atomically sets the gauge to the given value, returning the updated value.
5179 *
5280 * @return the updated value
5381 */
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 )
5684 return newValue
5785 }
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()
5894}
0 commit comments