本文整理汇总了Python中prometheus_client.Gauge类的典型用法代码示例。如果您正苦于以下问题:Python Gauge类的具体用法?Python Gauge怎么用?Python Gauge使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Gauge类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
class PrometheusClient:
def __init__(self):
# # Start up the server to expose the metrics.
start_http_server(EXPORT_PORT)
self.g = Gauge('sensor_data', 'Value gathered by sensor', ['sensor_id', 'ipe_id', 'category_id', 'unit'])
def export_data(self, xml_data=None):
root = ET.fromstring(xml_data)
ipe_id = root.find('./*[@name="ipeId"]').attrib['val']
app_id = root.find('./*[@name="appId"]').attrib['val']
category = root.find('./*[@name="category"]').attrib['val']
data = int(root.find('./*[@name="data"]').attrib['val'])
unit = root.find('./*[@name="unit"]').attrib['val']
# json_body = [
# {
# "measurement": "sensor_status",
# "tags": {
# "sensor_id": app_id,
# "ipe_id": ipe_id,
# "category": category
# },
# "fields": {
# "data": data,
# "unit": unit
# }
# }
# ]
self.g.labels(app_id, ipe_id, category, unit).set(data)
示例2: dec_counter
def dec_counter(self, key, amount=1):
""" Decrement metric
"""
prometheus_counter = Gauge( # pylint: disable=no-value-for-parameter
key
)
prometheus_counter.dec(amount)
示例3: inc_counter
def inc_counter(self, key, amount=1):
""" Increment counter
"""
prometheus_counter = Gauge( # pylint: disable=no-value-for-parameter
key
)
prometheus_counter.inc(amount)
示例4: get_stats
def get_stats(self):
registry = CollectorRegistry()
labels = ['region']
label_values = [self.region]
duration = Gauge('openstack_exporter_cache_refresh_duration_seconds',
'Cache refresh duration in seconds.',
labels, registry=registry)
duration.labels(*label_values).set(self.duration)
return generate_latest(registry)
示例5: increment
def increment(self, stat, by=1):
self.stats[stat] += by
# Update the associated Prometheus gauge.
if stat not in self.prom_gauges:
gauge = Gauge(sanitize_name("felix_" + self.name + " " + stat),
"%s: %s" % (self.name, stat))
self.prom_gauges[stat] = gauge
else:
gauge = self.prom_gauges[stat]
gauge.inc(by)
示例6: export_metric
def export_metric(device, id, type, value):
global temperature_gauge
if (temperature_gauge == None):
temperature_gauge = Gauge('temperature', 'Temperatures from MQTT', ['device', 'id', 'type'])
global gauges
if (not id in gauges):
gauges[id] = temperature_gauge.labels(device, id, type)
logging.debug('New gauge added. Device: ' + device + ' Id: ' + str(id) + ', type: ' + type)
gauges[id].set(value)
logging.debug('Gauge temperature set with value: ' + str(value) + ' - Device: ' + device + ' Id: ' + id + ' Type: ' + type)
示例7: HistogramRoller
class HistogramRoller(RollerBase):
"""Accepts a Histogram object and creates a guage with multiple labels tracking bucket values
over a given time period.
"""
def __init__(self, histogram, options=None, registry=REGISTRY, roller_registry=ROLLER_REGISTRY):
self.hist = histogram
if self.hist._type != 'histogram':
raise ValueError('Only a Histogram object should be passed to HistogramRoller')
options = options or {}
self.extract_options(options)
# Keys are 'le' values
# Holds deques containing values for each gauge
self.past_values = dict()
full_name = ""
for full_name, labels, _ in iter_hist_buckets(self.hist):
le_label = labels['le']
self.past_values[le_label] = deque()
self.configure_with_full_name(full_name, is_histogram=True)
# A single top level gauge with bucket labels tracks the values
self.gauge = Gauge(
self.name,
self.documentation,
labelnames=('le',),
registry=registry
)
roller_registry[self.name] = self
def collect(self):
"""Loop over current histogram bucket values and update gauges.
Usage:
* Collect should only be called about every second, not in a tight loop.
* Should only be called in 1 thread at a time.
"""
now = datetime.datetime.now()
# Fetch values from histograms
for _, labels, value in iter_hist_buckets(self.hist):
sample_key = labels['le']
# Add value
self.past_values[sample_key].append((now, value))
# Drop old values
remove_old_values(self.past_values[sample_key], now - self.retention_td)
# Calculate and record new rolled value
v = self.reducer(values_to_deltas(self.past_values[sample_key]), **self.reducer_kwargs)
self.gauge.labels({'le': sample_key}).set(v)
示例8: sendGauge
def sendGauge(self,metric, description ,value, job, labels):
for g in self.metrics:
if g._name == metric and g._type == 'gauge':
g.labels(resource_id=self.id,snmp_ip=labels['ip'],snmp_port=labels['port']).set(value)
self.push(job=job)
return
g = Gauge(metric, description , ["resource_id","snmp_ip","snmp_port"], registry=self.registry)
g.labels(resource_id=self.id,snmp_ip=labels['ip'],snmp_port=labels['port']).set(value)
self.metrics.append(g)
self.push(job=job)
示例9: PrometheusMetricsCollector
class PrometheusMetricsCollector(MetricsCollector):
def __init__(self):
super(PrometheusMetricsCollector, self).__init__()
self.registry = CollectorRegistry()
self.task_started_counter = Counter(
'luigi_task_started_total',
'number of started luigi tasks',
['family'],
registry=self.registry
)
self.task_failed_counter = Counter(
'luigi_task_failed_total',
'number of failed luigi tasks',
['family'],
registry=self.registry
)
self.task_disabled_counter = Counter(
'luigi_task_disabled_total',
'number of disabled luigi tasks',
['family'],
registry=self.registry
)
self.task_done_counter = Counter(
'luigi_task_done_total',
'number of done luigi tasks',
['family'],
registry=self.registry
)
self.task_execution_time = Gauge(
'luigi_task_execution_time_seconds',
'luigi task execution time in seconds',
['family'],
registry=self.registry
)
def generate_latest(self):
return generate_latest(self.registry)
def handle_task_started(self, task):
self.task_started_counter.labels(family=task.family).inc()
self.task_execution_time.labels(family=task.family)
def handle_task_failed(self, task):
self.task_failed_counter.labels(family=task.family).inc()
self.task_execution_time.labels(family=task.family).set(task.updated - task.time_running)
def handle_task_disabled(self, task, config):
self.task_disabled_counter.labels(family=task.family).inc()
self.task_execution_time.labels(family=task.family).set(task.updated - task.time_running)
def handle_task_done(self, task):
self.task_done_counter.labels(family=task.family).inc()
# time_running can be `None` if task was already complete
if task.time_running is not None:
self.task_execution_time.labels(family=task.family).set(task.updated - task.time_running)
def configure_http_handler(self, http_handler):
http_handler.set_header('Content-Type', CONTENT_TYPE_LATEST)
示例10: __init__
def __init__(self, histogram, options=None, registry=REGISTRY, roller_registry=ROLLER_REGISTRY):
self.hist = histogram
if self.hist._type != 'histogram':
raise ValueError('Only a Histogram object should be passed to HistogramRoller')
options = options or {}
self.extract_options(options)
# Keys are 'le' values
# Holds deques containing values for each gauge
self.past_values = dict()
full_name = ""
for full_name, labels, _ in iter_hist_buckets(self.hist):
le_label = labels['le']
self.past_values[le_label] = deque()
self.configure_with_full_name(full_name, is_histogram=True)
# A single top level gauge with bucket labels tracks the values
self.gauge = Gauge(
self.name,
self.documentation,
labelnames=('le',),
registry=registry
)
roller_registry[self.name] = self
示例11: __init__
def __init__(self):
super(PrometheusMetricsCollector, self).__init__()
self.registry = CollectorRegistry()
self.task_started_counter = Counter(
'luigi_task_started_total',
'number of started luigi tasks',
['family'],
registry=self.registry
)
self.task_failed_counter = Counter(
'luigi_task_failed_total',
'number of failed luigi tasks',
['family'],
registry=self.registry
)
self.task_disabled_counter = Counter(
'luigi_task_disabled_total',
'number of disabled luigi tasks',
['family'],
registry=self.registry
)
self.task_done_counter = Counter(
'luigi_task_done_total',
'number of done luigi tasks',
['family'],
registry=self.registry
)
self.task_execution_time = Gauge(
'luigi_task_execution_time_seconds',
'luigi task execution time in seconds',
['family'],
registry=self.registry
)
示例12: get_stats
def get_stats(self):
registry = CollectorRegistry()
labels = ['region', 'host', 'service', 'state']
services_stats_cache = self.get_cache_data()
for services_stat in services_stats_cache:
stat_gauge = Gauge(
self.gauge_name_sanitize(
services_stat['stat_name']),
'Openstack Nova Service statistic',
labels,
registry=registry)
label_values = [self.osclient.region,
services_stat.get('host', ''),
services_stat.get('service', ''),
services_stat.get('state', '')]
stat_gauge.labels(*label_values).set(services_stat['stat_value'])
return generate_latest(registry)
示例13: get_stats
def get_stats(self):
registry = CollectorRegistry()
labels = ['region', 'host', 'aggregate', 'aggregate_id']
hypervisor_stats_cache = self.get_cache_data()
for hypervisor_stat in hypervisor_stats_cache:
stat_gauge = Gauge(
self.gauge_name_sanitize(
hypervisor_stat['stat_name']),
'Openstack Hypervisor statistic',
labels,
registry=registry)
label_values = [self.osclient.region,
hypervisor_stat.get('host', ''),
hypervisor_stat.get('aggregate', ''),
hypervisor_stat.get('aggregate_id', '')]
stat_gauge.labels(*label_values).set(hypervisor_stat['stat_value'])
return generate_latest(registry)
示例14: update_gauges
def update_gauges(metrics):
metric_dict = {}
for (name_list, label_dict, value) in metrics:
metric_name = format_metric_name(name_list)
if metric_name not in metric_dict:
metric_dict[metric_name] = (tuple(label_dict.keys()), {})
label_keys = metric_dict[metric_name][0]
label_values = tuple([
format_label_value(label_dict[key])
for key in label_keys
])
metric_dict[metric_name][1][label_values] = value
for metric_name, (label_keys, value_dict) in metric_dict.items():
if metric_name in gauges:
(old_label_values_set, gauge) = gauges[metric_name]
else:
old_label_values_set = set()
gauge = Gauge(metric_name, '', label_keys)
new_label_values_set = set(value_dict.keys())
for label_values in old_label_values_set - new_label_values_set:
gauge.remove(*label_values)
for label_values, value in value_dict.items():
if label_values:
gauge.labels(*label_values).set(value)
else:
gauge.set(value)
gauges[metric_name] = (new_label_values_set, gauge)
示例15: CounterRoller
class CounterRoller(RollerBase):
"""Accepts a Counter object and creates a gauge tracking its value over a given time period.
"""
def __init__(self, counter, options=None, registry=REGISTRY, roller_registry=ROLLER_REGISTRY):
self.counter = counter
if self.counter._type != 'counter':
raise ValueError('Only a Counter object should be passed to CounterRoller')
options = options or {}
self.extract_options(options)
self.past_values = deque()
full_name, _, _ = self.get_sample()
self.configure_with_full_name(full_name)
self.gauge = Gauge(
self.name,
self.documentation,
registry=registry
)
roller_registry[self.name] = self
def get_sample(self):
"""Returns (full_name, labels, value)
"""
return self.counter.collect()[0].samples[0]
def collect(self):
"""Update tracked counter values and current gauge value
"""
now = datetime.datetime.now()
# Fetch value from counter
_, _, value = self.get_sample()
# Add value
self.past_values.append((now, value))
# Drop old values
remove_old_values(self.past_values, now - self.retention_td)
# Calculate and record new rolled value
v = self.reducer(values_to_deltas(self.past_values), **self.reducer_kwargs)
self.gauge.set(v)