Skip to content

Commit 6b9e6de

Browse files
committed
Merge pull request prometheus#24 from brian-brazil/gauge-callback
Add support for callbacks for gauges.
2 parents f608ea4 + d183810 commit 6b9e6de

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

README.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,14 @@ with g.track_inprogress():
113113
pass
114114
```
115115

116+
A Gauge can also take it's value from a callback:
117+
118+
```python
119+
d = Gauge('data_objects', 'Number of objects')
120+
my_dict = {}
121+
d.set_function(lambda: len(my_dict))
122+
```
123+
116124
### Summary
117125

118126
Summaries track the size and number of events.

prometheus_client/__init__.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import os
99
import time
1010
import threading
11+
import types
1112
try:
1213
from BaseHTTPServer import BaseHTTPRequestHandler
1314
from BaseHTTPServer import HTTPServer
@@ -279,6 +280,17 @@ def wrapped(*args, **kwargs):
279280

280281
return InprogressTracker(self)
281282

283+
def set_function(self, f):
284+
'''Call the provided function to return the Gauge value.
285+
286+
The function must return a float, and may be called from
287+
multiple threads.
288+
All other methods of the Gauge become NOOPs.
289+
'''
290+
def samples(self):
291+
return (('', {}, float(f())), )
292+
self._samples = types.MethodType(samples, self)
293+
282294
def _samples(self):
283295
with self._lock:
284296
return (('', {}, self._value), )

tests/test_client.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,15 @@ def test_block_decorator(self):
8787
self.assertEqual(1, self.registry.get_sample_value('g'))
8888
self.assertEqual(0, self.registry.get_sample_value('g'))
8989

90+
def test_gauge_function(self):
91+
x = {}
92+
self.gauge.set_function(lambda: len(x))
93+
self.assertEqual(0, self.registry.get_sample_value('g'))
94+
self.gauge.inc()
95+
self.assertEqual(0, self.registry.get_sample_value('g'))
96+
x['a'] = None
97+
self.assertEqual(1, self.registry.get_sample_value('g'))
98+
9099

91100
class TestSummary(unittest.TestCase):
92101
def setUp(self):

0 commit comments

Comments
 (0)