0
# Core Metrics
1
2
The fundamental metric types in prometheus-client for collecting different kinds of measurements. Each metric type is designed for specific use cases and provides thread-safe operations with support for multi-dimensional labeling.
3
4
## Capabilities
5
6
### Counter
7
8
A monotonically increasing counter that can only increase or be reset to zero. Counters are ideal for measuring cumulative values like total requests, errors, or completed tasks.
9
10
```python { .api }
11
class Counter:
12
def __init__(
13
self,
14
name: str,
15
documentation: str,
16
labelnames: Iterable[str] = (),
17
namespace: str = '',
18
subsystem: str = '',
19
unit: str = '',
20
registry: Optional[CollectorRegistry] = REGISTRY,
21
_labelvalues: Optional[Sequence[str]] = None
22
) -> None:
23
"""
24
Create a new Counter metric.
25
26
Parameters:
27
- name: Metric name (without _total suffix)
28
- documentation: Help text describing the metric
29
- labelnames: Sequence of label names for multi-dimensional metrics
30
- namespace: Optional namespace prefix
31
- subsystem: Optional subsystem prefix
32
- unit: Optional unit suffix
33
- registry: Registry to register this metric with
34
"""
35
36
def inc(self, amount: float = 1, exemplar: Optional[Dict[str, str]] = None) -> None:
37
"""
38
Increment the counter by amount.
39
40
Parameters:
41
- amount: Amount to increment by (must be >= 0)
42
- exemplar: Optional exemplar for tracing
43
"""
44
45
def reset(self) -> None:
46
"""Reset the counter to zero."""
47
48
def count_exceptions(self, exception=Exception) -> ExceptionCounter:
49
"""
50
Return a context manager that counts exceptions.
51
52
Parameters:
53
- exception: Exception type to count
54
55
Returns:
56
ExceptionCounter context manager
57
"""
58
59
def labels(self, *labelvalues, **labelkwargs) -> Counter:
60
"""
61
Return the Counter for the given label values.
62
63
Parameters:
64
- labelvalues: Label values in order of labelnames
65
- labelkwargs: Label values as keyword arguments
66
67
Returns:
68
Counter instance for the specific label combination
69
"""
70
71
def remove(self, *labelvalues) -> None:
72
"""Remove a labeled metric."""
73
74
def clear(self) -> None:
75
"""Remove all labeled metrics."""
76
77
def describe(self) -> Iterable[Metric]:
78
"""Return metric metadata."""
79
80
def collect(self) -> Iterable[Metric]:
81
"""Return current metric samples."""
82
83
def __str__(self) -> str:
84
"""Return string representation."""
85
86
def __repr__(self) -> str:
87
"""Return detailed string representation."""
88
```
89
90
**Usage Example:**
91
92
```python
93
from prometheus_client import Counter
94
95
# Simple counter
96
requests_total = Counter('http_requests_total', 'Total HTTP requests')
97
requests_total.inc() # Increment by 1
98
requests_total.inc(5) # Increment by 5
99
100
# Counter with labels
101
requests_by_status = Counter(
102
'http_requests_total',
103
'Total HTTP requests',
104
['method', 'status']
105
)
106
requests_by_status.labels(method='GET', status='200').inc()
107
requests_by_status.labels('POST', '404').inc(2)
108
109
# Exception counting
110
with requests_total.count_exceptions():
111
# Code that might raise exceptions
112
risky_operation()
113
```
114
115
### Gauge
116
117
A gauge represents a single numerical value that can go up or down. Gauges are suitable for measured values like temperatures, current memory usage, or number of concurrent requests.
118
119
```python { .api }
120
class Gauge:
121
def __init__(
122
self,
123
name: str,
124
documentation: str,
125
labelnames: Iterable[str] = (),
126
namespace: str = '',
127
subsystem: str = '',
128
unit: str = '',
129
registry: Optional[CollectorRegistry] = REGISTRY,
130
_labelvalues: Optional[Sequence[str]] = None,
131
multiprocess_mode: Literal['all', 'liveall', 'min', 'livemin', 'max', 'livemax', 'sum', 'livesum', 'mostrecent', 'livemostrecent'] = 'all'
132
) -> None:
133
"""
134
Create a new Gauge metric.
135
136
Parameters:
137
- name: Metric name
138
- documentation: Help text describing the metric
139
- labelnames: Sequence of label names for multi-dimensional metrics
140
- namespace: Optional namespace prefix
141
- subsystem: Optional subsystem prefix
142
- unit: Optional unit suffix
143
- registry: Registry to register this metric with
144
- multiprocess_mode: How to aggregate in multiprocess mode ('all', 'liveall', 'min', 'livemin', 'max', 'livemax', 'sum', 'livesum', 'mostrecent', 'livemostrecent')
145
"""
146
147
def set(self, value: float) -> None:
148
"""Set the gauge to the given value."""
149
150
def inc(self, amount: float = 1) -> None:
151
"""Increment the gauge by amount."""
152
153
def dec(self, amount: float = 1) -> None:
154
"""Decrement the gauge by amount."""
155
156
def set_to_current_time(self) -> None:
157
"""Set the gauge to the current Unix timestamp."""
158
159
def track_inprogress(self) -> InprogressTracker:
160
"""
161
Return a context manager that tracks in-progress operations.
162
163
Returns:
164
InprogressTracker context manager
165
"""
166
167
def time(self) -> Timer:
168
"""
169
Return a context manager/decorator that times operations.
170
171
Returns:
172
Timer context manager
173
"""
174
175
def set_function(self, f: Callable[[], float]) -> None:
176
"""
177
Set the gauge to the return value of a function.
178
179
Parameters:
180
- f: Function that returns a float value
181
"""
182
183
def labels(self, *labelvalues, **labelkwargs) -> Gauge:
184
"""Return the Gauge for the given label values."""
185
186
def remove(self, *labelvalues) -> None:
187
"""Remove a labeled metric."""
188
189
def clear(self) -> None:
190
"""Remove all labeled metrics."""
191
192
def describe(self) -> Iterable[Metric]:
193
"""Return metric metadata."""
194
195
def collect(self) -> Iterable[Metric]:
196
"""Return current metric samples."""
197
198
def __str__(self) -> str:
199
"""Return string representation."""
200
201
def __repr__(self) -> str:
202
"""Return detailed string representation."""
203
```
204
205
**Usage Example:**
206
207
```python
208
from prometheus_client import Gauge
209
import psutil
210
211
# Simple gauge
212
memory_usage = Gauge('memory_usage_bytes', 'Current memory usage in bytes')
213
memory_usage.set(psutil.virtual_memory().used)
214
215
# Gauge with labels
216
cpu_usage = Gauge('cpu_usage_percent', 'CPU usage by core', ['core'])
217
for i, percent in enumerate(psutil.cpu_percent(percpu=True)):
218
cpu_usage.labels(core=str(i)).set(percent)
219
220
# Auto-updating gauge
221
def get_disk_usage():
222
return psutil.disk_usage('/').percent
223
224
disk_gauge = Gauge('disk_usage_percent', 'Disk usage percentage')
225
disk_gauge.set_function(get_disk_usage)
226
227
# Timing operations
228
response_time = Gauge('response_time_seconds', 'Response time')
229
with response_time.time():
230
# Timed operation
231
time.sleep(0.1)
232
233
# Tracking in-progress work
234
active_requests = Gauge('active_requests', 'Number of active requests')
235
with active_requests.track_inprogress():
236
# Process request
237
handle_request()
238
```
239
240
### Histogram
241
242
A histogram samples observations and counts them in configurable buckets, also providing sum and count of observations. Histograms are ideal for measuring request durations, response sizes, or any value where you want to understand the distribution.
243
244
```python { .api }
245
class Histogram:
246
DEFAULT_BUCKETS = (.005, .01, .025, .05, .075, .1, .25, .5, .75, 1.0, 2.5, 5.0, 7.5, 10.0, INF)
247
248
def __init__(
249
self,
250
name: str,
251
documentation: str,
252
labelnames: Iterable[str] = (),
253
namespace: str = '',
254
subsystem: str = '',
255
unit: str = '',
256
registry: Optional[CollectorRegistry] = REGISTRY,
257
_labelvalues: Optional[Sequence[str]] = None,
258
buckets: Sequence[Union[float, str]] = DEFAULT_BUCKETS
259
) -> None:
260
"""
261
Create a new Histogram metric.
262
263
Parameters:
264
- name: Metric name
265
- documentation: Help text describing the metric
266
- labelnames: Sequence of label names for multi-dimensional metrics
267
- namespace: Optional namespace prefix
268
- subsystem: Optional subsystem prefix
269
- unit: Optional unit suffix
270
- registry: Registry to register this metric with
271
- buckets: Sequence of bucket upper bounds
272
"""
273
274
def observe(self, amount: float, exemplar: Optional[Dict[str, str]] = None) -> None:
275
"""
276
Observe a value.
277
278
Parameters:
279
- amount: Value to observe
280
- exemplar: Optional exemplar for tracing
281
"""
282
283
def time(self) -> Timer:
284
"""
285
Return a context manager/decorator that times operations.
286
287
Returns:
288
Timer context manager that observes elapsed time
289
"""
290
291
def labels(self, *labelvalues, **labelkwargs) -> Histogram:
292
"""Return the Histogram for the given label values."""
293
294
def remove(self, *labelvalues) -> None:
295
"""Remove a labeled metric."""
296
297
def clear(self) -> None:
298
"""Remove all labeled metrics."""
299
```
300
301
**Usage Example:**
302
303
```python
304
from prometheus_client import Histogram
305
import time
306
import random
307
308
# Request duration histogram
309
request_duration = Histogram(
310
'http_request_duration_seconds',
311
'HTTP request duration in seconds',
312
['method', 'endpoint']
313
)
314
315
# Observe values
316
request_duration.labels('GET', '/api/users').observe(0.25)
317
request_duration.labels('POST', '/api/users').observe(0.8)
318
319
# Custom buckets for specific use case
320
response_size = Histogram(
321
'http_response_size_bytes',
322
'HTTP response size in bytes',
323
buckets=[100, 1000, 10000, 100000, 1000000, float('inf')]
324
)
325
response_size.observe(1024)
326
327
# Time operations automatically
328
with request_duration.labels('GET', '/api/health').time():
329
# Simulated work
330
time.sleep(random.uniform(0.1, 0.5))
331
332
# As a decorator
333
@request_duration.labels('POST', '/api/data').time()
334
def process_data():
335
time.sleep(random.uniform(0.2, 1.0))
336
return "processed"
337
```
338
339
### Summary
340
341
A summary samples observations and provides count and sum of observations, plus configurable quantiles over a sliding time window. Summaries are useful when you need quantile information (like median, 95th percentile) but want to avoid the overhead of histograms.
342
343
```python { .api }
344
class Summary:
345
def __init__(
346
self,
347
name: str,
348
documentation: str,
349
labelnames=(),
350
namespace='',
351
subsystem='',
352
unit='',
353
registry=REGISTRY,
354
_labelvalues=None
355
) -> None:
356
"""
357
Create a new Summary metric.
358
359
Parameters:
360
- name: Metric name
361
- documentation: Help text describing the metric
362
- labelnames: Sequence of label names for multi-dimensional metrics
363
- namespace: Optional namespace prefix
364
- subsystem: Optional subsystem prefix
365
- unit: Optional unit suffix
366
- registry: Registry to register this metric with
367
"""
368
369
def observe(self, amount: float) -> None:
370
"""
371
Observe a value.
372
373
Parameters:
374
- amount: Value to observe
375
"""
376
377
def time(self) -> Timer:
378
"""
379
Return a context manager/decorator that times operations.
380
381
Returns:
382
Timer context manager that observes elapsed time
383
"""
384
385
def labels(self, *labelvalues, **labelkwargs) -> Summary:
386
"""Return the Summary for the given label values."""
387
388
def remove(self, *labelvalues) -> None:
389
"""Remove a labeled metric."""
390
391
def clear(self) -> None:
392
"""Remove all labeled metrics."""
393
```
394
395
**Usage Example:**
396
397
```python
398
from prometheus_client import Summary
399
import time
400
import random
401
402
# Response time summary
403
response_time = Summary(
404
'http_response_time_seconds',
405
'HTTP response time in seconds',
406
['service']
407
)
408
409
# Observe values
410
response_time.labels('auth').observe(0.12)
411
response_time.labels('database').observe(0.045)
412
413
# Time operations
414
with response_time.labels('api').time():
415
# Simulated API call
416
time.sleep(random.uniform(0.05, 0.2))
417
```
418
419
### Info
420
421
An info metric represents a set of key-value pairs. It is useful for exposing textual information like version numbers, build information, or configuration details.
422
423
```python { .api }
424
class Info:
425
def __init__(
426
self,
427
name: str,
428
documentation: str,
429
labelnames=(),
430
namespace='',
431
subsystem='',
432
registry=REGISTRY,
433
_labelvalues=None
434
) -> None:
435
"""
436
Create a new Info metric.
437
438
Parameters:
439
- name: Metric name
440
- documentation: Help text describing the metric
441
- labelnames: Sequence of label names for multi-dimensional metrics
442
- namespace: Optional namespace prefix
443
- subsystem: Optional subsystem prefix
444
- registry: Registry to register this metric with
445
"""
446
447
def info(self, val: Dict[str, str]) -> None:
448
"""
449
Set the info metric with key-value pairs.
450
451
Parameters:
452
- val: Dictionary of string key-value pairs
453
"""
454
455
def labels(self, *labelvalues, **labelkwargs) -> Info:
456
"""Return the Info for the given label values."""
457
458
def remove(self, *labelvalues) -> None:
459
"""Remove a labeled metric."""
460
461
def clear(self) -> None:
462
"""Remove all labeled metrics."""
463
```
464
465
**Usage Example:**
466
467
```python
468
from prometheus_client import Info
469
import sys
470
import platform
471
472
# Application info
473
app_info = Info('app_info', 'Application information')
474
app_info.info({
475
'version': '1.2.3',
476
'python_version': sys.version.split()[0],
477
'platform': platform.system(),
478
'build_date': '2023-10-15'
479
})
480
481
# Environment-specific info
482
env_info = Info('environment_info', 'Environment information', ['env'])
483
env_info.labels('production').info({
484
'datacenter': 'us-east-1',
485
'cluster': 'prod-cluster-01'
486
})
487
```
488
489
### Enum
490
491
An enum metric represents a state set where exactly one of a set of states is true. It's useful for representing the current state of a system or component.
492
493
```python { .api }
494
class Enum:
495
def __init__(
496
self,
497
name: str,
498
documentation: str,
499
labelnames=(),
500
namespace='',
501
subsystem='',
502
registry=REGISTRY,
503
_labelvalues=None,
504
states=None
505
) -> None:
506
"""
507
Create a new Enum metric.
508
509
Parameters:
510
- name: Metric name
511
- documentation: Help text describing the metric
512
- labelnames: Sequence of label names for multi-dimensional metrics
513
- namespace: Optional namespace prefix
514
- subsystem: Optional subsystem prefix
515
- registry: Registry to register this metric with
516
- states: Sequence of possible state names
517
"""
518
519
def state(self, state: str) -> None:
520
"""
521
Set the current state.
522
523
Parameters:
524
- state: Name of the current state
525
"""
526
527
def labels(self, *labelvalues, **labelkwargs) -> Enum:
528
"""Return the Enum for the given label values."""
529
530
def remove(self, *labelvalues) -> None:
531
"""Remove a labeled metric."""
532
533
def clear(self) -> None:
534
"""Remove all labeled metrics."""
535
```
536
537
**Usage Example:**
538
539
```python
540
from prometheus_client import Enum
541
542
# Service status
543
service_status = Enum(
544
'service_status',
545
'Current service status',
546
states=['starting', 'running', 'stopping', 'stopped']
547
)
548
549
# Set current state
550
service_status.state('running')
551
552
# With labels for multiple services
553
component_status = Enum(
554
'component_status',
555
'Component status',
556
['component'],
557
states=['healthy', 'degraded', 'unhealthy']
558
)
559
560
component_status.labels('database').state('healthy')
561
component_status.labels('cache').state('degraded')
562
```
563
564
## Configuration Functions
565
566
```python { .api }
567
def enable_created_metrics() -> None:
568
"""Enable exporting _created metrics on counters, histograms, and summaries."""
569
570
def disable_created_metrics() -> None:
571
"""Disable exporting _created metrics on counters, histograms, and summaries."""
572
```
573
574
**Usage Example:**
575
576
```python
577
from prometheus_client import enable_created_metrics, disable_created_metrics
578
579
# Control _created series export
580
enable_created_metrics() # Enable timestamp tracking
581
disable_created_metrics() # Disable timestamp tracking (saves memory)
582
```