本文整理汇总了Python中prometheus_client.Gauge.labels方法的典型用法代码示例。如果您正苦于以下问题:Python Gauge.labels方法的具体用法?Python Gauge.labels怎么用?Python Gauge.labels使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类prometheus_client.Gauge
的用法示例。
在下文中一共展示了Gauge.labels方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: update_gauges
# 需要导入模块: from prometheus_client import Gauge [as 别名]
# 或者: from prometheus_client.Gauge import labels [as 别名]
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)
示例2: __init__
# 需要导入模块: from prometheus_client import Gauge [as 别名]
# 或者: from prometheus_client.Gauge import labels [as 别名]
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)
示例3: get_stats
# 需要导入模块: from prometheus_client import Gauge [as 别名]
# 或者: from prometheus_client.Gauge import labels [as 别名]
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)
示例4: HistogramRoller
# 需要导入模块: from prometheus_client import Gauge [as 别名]
# 或者: from prometheus_client.Gauge import labels [as 别名]
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)
示例5: sendGauge
# 需要导入模块: from prometheus_client import Gauge [as 别名]
# 或者: from prometheus_client.Gauge import labels [as 别名]
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)
示例6: register_prometheus_gauges
# 需要导入模块: from prometheus_client import Gauge [as 别名]
# 或者: from prometheus_client.Gauge import labels [as 别名]
def register_prometheus_gauges(export_internal_raspberry=False):
g = Gauge("sensor_temperature_in_celsius", "Local room temperature around the raspberry pi", ["sensor"])
error_g = Gauge("faulty_sensor_read", "Is 1 if the sensor could not be read.", ["sensor"])
sensors = find_sensors()
print "Found sensors:", ", ".join(map(lambda x: str(x), sensors))
for sensor in sensors:
g.labels(str(sensor)).set_function(sensor)
sensor.set_error_gauge(error_g.labels(str(sensor)))
if export_internal_raspberry:
g = Gauge("cpu_temperature_in_celsius", "CPU Temperature of the Raspberry Pi")
g.set_function(read_raspberry_pi_temperature)
return sensors
示例7: gather_data
# 需要导入模块: from prometheus_client import Gauge [as 别名]
# 或者: from prometheus_client.Gauge import labels [as 别名]
def gather_data(namespace, run_event):
g_cpu_usage = Gauge("cpu_cumulative_usage", "CPU Cumulative Usage", ["service", "instance"])
g_cpu_utilization = Gauge('cpu_utilization', "CPU utilization", ["service", "instance"])
g_memory_usage = Gauge('memory_usage', "Memory Usage", ["servie", "instance"])
g_memory_utilization = Gauge('memory_utilization', "Memory Utilization", ["service", "instance"])
while run_event.is_set():
service_list = alauda_service_list(namespace)
for service_inst in service_list:
service_name = service_inst.name
instance_list = alauda_instance_list(namespace, service_name)
for instance in instance_list:
end_time = int(time.time()) - 30
start_time = str(end_time - 100) #gather data every 1 minute, ensure we can get at least one metric
end_time = str(end_time)
data = alauda_get_instance_metrics(namespace, service_name, instance['uuid'], start_time, end_time, "1m")
if data:
g_cpu_usage.labels(service_name, instance['instance_name']).set(data['points'][0][1])
g_cpu_utilization.labels(service_name, instance['instance_name']).set(data['points'][0][2])
g_memory_usage.labels(service_name, instance['instance_name']).set(data['points'][0][3])
g_memory_utilization.labels(service_name, instance['instance_name']).set(data['points'][0][4])
time.sleep(20)
示例8: PrometheusMetricsCollector
# 需要导入模块: from prometheus_client import Gauge [as 别名]
# 或者: from prometheus_client.Gauge import labels [as 别名]
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)
示例9: get_prometheus_inventory_metrics
# 需要导入模块: from prometheus_client import Gauge [as 别名]
# 或者: from prometheus_client.Gauge import labels [as 别名]
def get_prometheus_inventory_metrics():
registry = CollectorRegistry()
g = Gauge('zentral_inventory_osx_apps', 'Zentral inventory OSX apps',
['name', 'version_str', 'source'],
registry=registry)
for r in osx_app_count():
count = r.pop('count')
g.labels(**r).set(count)
g = Gauge('zentral_inventory_os_versions', 'Zentral inventory OS Versions',
['name', 'major', 'minor', 'patch', 'build', 'source'],
registry=registry)
for r in os_version_count():
count = r.pop('count')
g.labels(**r).set(count)
return generate_latest(registry)
示例10: get_stats
# 需要导入模块: from prometheus_client import Gauge [as 别名]
# 或者: from prometheus_client.Gauge import labels [as 别名]
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)
示例11: get_stats
# 需要导入模块: from prometheus_client import Gauge [as 别名]
# 或者: from prometheus_client.Gauge import labels [as 别名]
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)
示例12: get_stats
# 需要导入模块: from prometheus_client import Gauge [as 别名]
# 或者: from prometheus_client.Gauge import labels [as 别名]
def get_stats(self):
registry = CollectorRegistry()
labels = ['region', 'url', 'service']
check_api_data_cache = self.get_cache_data()
for check_api_data in check_api_data_cache:
label_values = [
check_api_data['region'],
check_api_data['url'],
check_api_data['service']]
gague_name = self.gauge_name_sanitize(
"check_{}_api".format(check_api_data['service']))
check_gauge = Gauge(
gague_name,
'Openstack API check. fail = 0, ok = 1 and unknown = 2',
labels,
registry=registry)
check_gauge.labels(*label_values).set(check_api_data['status'])
return generate_latest(registry)
示例13: push_inventory_metrics
# 需要导入模块: from prometheus_client import Gauge [as 别名]
# 或者: from prometheus_client.Gauge import labels [as 别名]
def push_inventory_metrics():
ppg = settings.get('apps', {}).get('zentral.contrib.inventory', {}).get('prometheus_push_gateway', None)
if not ppg:
return
registry = CollectorRegistry()
g = Gauge('zentral_inventory_osx_apps', 'Zentral inventory OSX apps',
['name', 'version_str', 'source'],
registry=registry)
for r in osx_app_count():
count = r.pop('count')
g.labels(r).set(count)
g = Gauge('zentral_inventory_os_versions', 'Zentral inventory OS Versions',
['name', 'major', 'minor', 'patch', 'build', 'source'],
registry=registry)
for r in os_version_count():
count = r.pop('count')
g.labels(r).set(count)
push_to_gateway(ppg, job='zentral_push_inventory_metrics', registry=registry)
示例14: __init__
# 需要导入模块: from prometheus_client import Gauge [as 别名]
# 或者: from prometheus_client.Gauge import labels [as 别名]
class PromClient: # pylint: disable=too-few-public-methods
"""Prometheus client."""
REQUIRED_LABELS = ['dp_id', 'dp_name']
_reg = REGISTRY
def __init__(self, reg=None):
if reg is not None:
self._reg = reg
# TODO: investigate faster alternative (https://bugs.launchpad.net/pbr/+bug/1688405)
version = VersionInfo('faucet').semantic_version().release_string()
self.faucet_version = PromGauge( # pylint: disable=unexpected-keyword-arg
'faucet_pbr_version',
'Faucet PBR version',
['version'],
registry=self._reg)
self.faucet_version.labels(version=version).set(1) # pylint: disable=no-member
self.server = None
self.thread = None
def start(self, prom_port, prom_addr, use_test_thread=False):
"""Start webserver."""
if not self.server:
app = make_wsgi_app(self._reg)
if use_test_thread:
from wsgiref.simple_server import make_server, WSGIRequestHandler
import threading
class NoLoggingWSGIRequestHandler(WSGIRequestHandler):
"""Don't log requests."""
def log_message(self, *_args): # pylint: disable=arguments-differ
pass
self.server = make_server(
prom_addr, int(prom_port), app, handler_class=NoLoggingWSGIRequestHandler)
self.thread = threading.Thread(target=self.server.serve_forever)
self.thread.daemon = True
self.thread.start()
else:
self.server = hub.WSGIServer((prom_addr, int(prom_port)), app)
self.thread = hub.spawn(self.server.serve_forever)
self.thread.name = 'prometheus'
示例15: export_metric
# 需要导入模块: from prometheus_client import Gauge [as 别名]
# 或者: from prometheus_client.Gauge import labels [as 别名]
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)