0
# Prometheus Client
1
2
The official Python client library for Prometheus, providing comprehensive instrumentation capabilities for collecting and exposing metrics. This library enables applications to define, collect, and export metrics in Prometheus format, supporting counters, gauges, histograms, summaries, and specialized metric types for monitoring application performance and system health.
3
4
## Package Information
5
6
- **Package Name**: prometheus-client
7
- **Language**: Python
8
- **Installation**: `pip install prometheus-client`
9
10
## Core Imports
11
12
```python
13
import prometheus_client
14
```
15
16
Most common imports for metrics:
17
18
```python
19
from prometheus_client import Counter, Gauge, Histogram, Summary, Info, Enum
20
```
21
22
Registry and exposition:
23
24
```python
25
from prometheus_client import REGISTRY, generate_latest, start_http_server
26
```
27
28
## Basic Usage
29
30
```python
31
from prometheus_client import Counter, Gauge, start_http_server
32
import time
33
import random
34
35
# Create metrics
36
request_count = Counter('http_requests_total', 'Total HTTP requests', ['method', 'status'])
37
response_time = Gauge('http_response_time_seconds', 'HTTP response time')
38
39
# Use metrics
40
request_count.labels(method='GET', status='200').inc()
41
response_time.set(0.25)
42
43
# Start metrics server
44
start_http_server(8000)
45
46
# Keep the application running
47
while True:
48
# Simulate some work
49
request_count.labels(method='GET', status='200').inc()
50
response_time.set(random.uniform(0.1, 0.5))
51
time.sleep(1)
52
```
53
54
## Architecture
55
56
The prometheus-client library is built around several key components:
57
58
- **Metrics**: Core measurement types (Counter, Gauge, Histogram, Summary, Info, Enum) that collect data
59
- **Registry**: Central collection point that manages all metrics and their metadata
60
- **Collectors**: Components that generate metrics data, including built-in system collectors
61
- **Exposition**: Functions and servers that output metrics in Prometheus format for scraping
62
- **Context Managers**: Utilities for automatic instrumentation of timing, exceptions, and progress tracking
63
64
This design provides thread-safe metric collection, flexible labeling for multi-dimensional data, and multiple exposition methods to integrate with various deployment architectures.
65
66
## Utility Functions
67
68
Global configuration and utility functions for metric management.
69
70
```python { .api }
71
def enable_created_metrics() -> None:
72
"""Enable exporting _created metrics on counters, histograms, and summaries."""
73
74
def disable_created_metrics() -> None:
75
"""Disable exporting _created metrics on counters, histograms, and summaries."""
76
77
def floatToGoString(d: float) -> str:
78
"""Convert float to Go-style string representation."""
79
80
def instance_ip_grouping_key() -> Dict[str, str]:
81
"""Return grouping key with instance IP for push gateway."""
82
```
83
84
**Usage Example:**
85
86
```python
87
from prometheus_client import enable_created_metrics, disable_created_metrics
88
89
# Control _created series export for better performance
90
disable_created_metrics() # Disable to save memory and bandwidth
91
# ... create metrics ...
92
enable_created_metrics() # Re-enable if needed
93
```
94
95
## Capabilities
96
97
### Core Metrics
98
99
The fundamental metric types for collecting different kinds of measurements, including monotonic counters, up/down gauges, distribution histograms, statistical summaries, and key-value info metrics.
100
101
```python { .api }
102
class Counter:
103
def __init__(self, name: str, documentation: str, labelnames=(), namespace='', subsystem='', unit='', registry=REGISTRY) -> None: ...
104
def inc(self, amount: float = 1, exemplar: Optional[Dict[str, str]] = None) -> None: ...
105
def labels(self, *labelvalues, **labelkwargs) -> Counter: ...
106
107
class Gauge:
108
def __init__(self, name: str, documentation: str, labelnames=(), namespace='', subsystem='', unit='', registry=REGISTRY, multiprocess_mode='all') -> None: ...
109
def set(self, value: float) -> None: ...
110
def inc(self, amount: float = 1) -> None: ...
111
def dec(self, amount: float = 1) -> None: ...
112
def labels(self, *labelvalues, **labelkwargs) -> Gauge: ...
113
114
class Histogram:
115
def __init__(self, name: str, documentation: str, labelnames=(), namespace='', subsystem='', unit='', registry=REGISTRY, buckets=DEFAULT_BUCKETS) -> None: ...
116
def observe(self, amount: float, exemplar: Optional[Dict[str, str]] = None) -> None: ...
117
def labels(self, *labelvalues, **labelkwargs) -> Histogram: ...
118
119
class Summary:
120
def __init__(self, name: str, documentation: str, labelnames=(), namespace='', subsystem='', unit='', registry=REGISTRY) -> None: ...
121
def observe(self, amount: float) -> None: ...
122
def labels(self, *labelvalues, **labelkwargs) -> Summary: ...
123
124
class Info:
125
def __init__(self, name: str, documentation: str, labelnames=(), namespace='', subsystem='', registry=REGISTRY) -> None: ...
126
def info(self, val: Dict[str, str]) -> None: ...
127
128
class Enum:
129
def __init__(self, name: str, documentation: str, labelnames=(), namespace='', subsystem='', registry=REGISTRY, states=None) -> None: ...
130
def state(self, state: str) -> None: ...
131
```
132
133
[Core Metrics](./core-metrics.md)
134
135
### Registry and Collection
136
137
The registry system that manages metric collection, organization, and retrieval, providing centralized access to all metrics and enabling custom collectors.
138
139
```python { .api }
140
class CollectorRegistry:
141
def __init__(self, auto_describe: bool = False, target_info: Optional[Dict[str, str]] = None) -> None: ...
142
def register(self, collector: Collector) -> None: ...
143
def unregister(self, collector: Collector) -> None: ...
144
def collect(self) -> Iterable[Metric]: ...
145
def get_sample_value(self, name: str, labels: Optional[Dict[str, str]] = None) -> Optional[float]: ...
146
147
REGISTRY: CollectorRegistry # Global default registry
148
```
149
150
[Registry System](./registry.md)
151
152
### Exposition and Servers
153
154
Functions and servers for outputting metrics in Prometheus format, including HTTP servers, WSGI/ASGI applications, file output, and push gateway integration.
155
156
```python { .api }
157
def generate_latest(registry: CollectorRegistry = REGISTRY) -> bytes: ...
158
def start_http_server(port: int, addr: str = '0.0.0.0', registry: CollectorRegistry = REGISTRY) -> Tuple[WSGIServer, threading.Thread]: ...
159
def make_wsgi_app(registry: CollectorRegistry = REGISTRY, disable_compression: bool = False) -> Callable: ...
160
def make_asgi_app(registry: CollectorRegistry = REGISTRY, disable_compression: bool = False) -> Callable: ...
161
def write_to_textfile(path: str, registry: CollectorRegistry) -> None: ...
162
163
def push_to_gateway(gateway: str, job: str, registry: CollectorRegistry, grouping_key=None, timeout: Optional[float] = 30) -> None: ...
164
def pushadd_to_gateway(gateway: str, job: str, registry: Optional[CollectorRegistry], grouping_key=None, timeout: Optional[float] = 30) -> None: ...
165
def delete_from_gateway(gateway: str, job: str, grouping_key=None, timeout: Optional[float] = 30) -> None: ...
166
```
167
168
[Exposition](./exposition.md)
169
170
### Built-in Collectors
171
172
Pre-built collectors for system metrics including process statistics, garbage collection data, and platform information that can be automatically registered for comprehensive monitoring.
173
174
```python { .api }
175
class ProcessCollector:
176
def __init__(self, namespace: str = '', pid: Callable = lambda: 'self', proc: str = '/proc', registry: Optional[CollectorRegistry] = REGISTRY) -> None: ...
177
178
class GCCollector:
179
def __init__(self, registry: CollectorRegistry = REGISTRY) -> None: ...
180
181
class PlatformCollector:
182
def __init__(self, registry: Optional[CollectorRegistry] = REGISTRY, platform=None) -> None: ...
183
184
PROCESS_COLLECTOR: ProcessCollector # Default process collector
185
GC_COLLECTOR: GCCollector # Default GC collector
186
PLATFORM_COLLECTOR: PlatformCollector # Default platform collector
187
```
188
189
[Built-in Collectors](./collectors.md)
190
191
### Context Managers and Utilities
192
193
Context managers and decorators for automatic instrumentation including timing operations, counting exceptions, and tracking in-progress work.
194
195
```python { .api }
196
class Timer:
197
def __enter__(self): ...
198
def __exit__(self, typ, value, traceback): ...
199
def __call__(self, f) -> Callable: ... # Decorator usage
200
201
class ExceptionCounter:
202
def __enter__(self) -> None: ...
203
def __exit__(self, typ, value, traceback) -> bool: ...
204
def __call__(self, f) -> Callable: ... # Decorator usage
205
206
class InprogressTracker:
207
def __enter__(self): ...
208
def __exit__(self, typ, value, traceback): ...
209
def __call__(self, f) -> Callable: ... # Decorator usage
210
```
211
212
[Context Managers](./context-managers.md)
213
214
### Custom Collectors and Advanced Features
215
216
Advanced functionality for building custom metric collectors, multiprocess support, and specialized integrations including metric families, sample types, and bridge components.
217
218
```python { .api }
219
class Metric:
220
def __init__(self, name: str, documentation: str, typ: str, unit: str = '') -> None: ...
221
def add_sample(self, name: str, labels: Dict[str, str], value: float, timestamp=None, exemplar=None) -> None: ...
222
223
class Collector:
224
def collect(self) -> Iterable[Metric]: ... # Abstract method
225
226
class MultiProcessCollector:
227
def __init__(self, registry, path=None) -> None: ...
228
```
229
230
[Advanced Features](./advanced.md)
231
232
## Types
233
234
```python { .api }
235
from typing import Dict, Optional, Iterable, Callable, Union, Sequence, NamedTuple, Literal
236
237
# Sample and data types
238
class Sample(NamedTuple):
239
name: str
240
labels: Dict[str, str]
241
value: float
242
timestamp: Optional[Union[float, Timestamp]] = None
243
exemplar: Optional[Exemplar] = None
244
native_histogram: Optional[NativeHistogram] = None
245
246
class Exemplar(NamedTuple):
247
labels: Dict[str, str]
248
value: float
249
timestamp: Optional[Union[float, Timestamp]] = None
250
251
class Timestamp:
252
def __init__(self, sec: float, nsec: float) -> None: ...
253
def __float__(self) -> float: ...
254
255
class BucketSpan(NamedTuple):
256
offset: int
257
length: int
258
259
class NativeHistogram(NamedTuple):
260
schema: int
261
zero_threshold: float
262
zero_count: int
263
count: int
264
sum: float
265
positive_spans: Sequence[BucketSpan]
266
positive_deltas: Sequence[int]
267
negative_spans: Sequence[BucketSpan]
268
negative_deltas: Sequence[int]
269
270
# Metric metadata
271
class Metric:
272
def __init__(self, name: str, documentation: str, typ: str, unit: str = '') -> None: ...
273
def add_sample(self, name: str, labels: Dict[str, str], value: float,
274
timestamp: Optional[Union[float, Timestamp]] = None,
275
exemplar: Optional[Exemplar] = None,
276
native_histogram: Optional[NativeHistogram] = None) -> None: ...
277
278
# Base collector interface
279
class Collector:
280
def collect(self) -> Iterable[Metric]: ...
281
def describe(self) -> Iterable[Metric]: ...
282
283
# Registry
284
class CollectorRegistry:
285
def __init__(self, auto_describe: bool = False, target_info: Optional[Dict[str, str]] = None) -> None: ...
286
def register(self, collector: Collector) -> None: ...
287
def unregister(self, collector: Collector) -> None: ...
288
def collect(self) -> Iterable[Metric]: ...
289
def get_sample_value(self, name: str, labels: Optional[Dict[str, str]] = None) -> Optional[float]: ...
290
291
# Constants
292
INF: float = float("inf")
293
MINUS_INF: float = float("-inf")
294
NaN: float = float("NaN")
295
CONTENT_TYPE_LATEST: str = 'text/plain; version=0.0.4; charset=utf-8'
296
297
# Global registry instance
298
REGISTRY: CollectorRegistry
299
300
# Validation and utility functions
301
def enable_created_metrics() -> None: ...
302
def disable_created_metrics() -> None: ...
303
def floatToGoString(d: float) -> str: ...
304
```