本文整理汇总了Python中prometheus_client.core.GaugeMetricFamily方法的典型用法代码示例。如果您正苦于以下问题:Python core.GaugeMetricFamily方法的具体用法?Python core.GaugeMetricFamily怎么用?Python core.GaugeMetricFamily使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类prometheus_client.core
的用法示例。
在下文中一共展示了core.GaugeMetricFamily方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: gauge_generator
# 需要导入模块: from prometheus_client import core [as 别名]
# 或者: from prometheus_client.core import GaugeMetricFamily [as 别名]
def gauge_generator(metrics):
metric_dict = group_metrics(metrics)
for metric_name, (metric_doc, label_keys, value_dict) in metric_dict.items():
# If we have label keys we may have multiple different values,
# each with their own label values.
if label_keys:
gauge = GaugeMetricFamily(metric_name, metric_doc, labels=label_keys)
for label_values in sorted(value_dict.keys()):
value = value_dict[label_values]
gauge.add_metric(tuple(str(v) for v in label_values), value)
# No label keys, so we must have only a single value.
else:
gauge = GaugeMetricFamily(metric_name, metric_doc, value=list(value_dict.values())[0])
yield gauge
示例2: collect
# 需要导入模块: from prometheus_client import core [as 别名]
# 或者: from prometheus_client.core import GaugeMetricFamily [as 别名]
def collect(self): # pylint: disable=missing-docstring
status_metrics = GaugeMetricFamily(
'pve_up',
'Node/VM/CT-Status is online/running',
labels=['id'])
for entry in self._pve.cluster.status.get():
if entry['type'] == 'node':
label_values = [entry['id']]
status_metrics.add_metric(label_values, entry['online'])
elif entry['type'] == 'cluster':
label_values = ['cluster/{:s}'.format(entry['name'])]
status_metrics.add_metric(label_values, entry['quorate'])
else:
raise ValueError('Got unexpected status entry type {:s}'.format(entry['type']))
for resource in self._pve.cluster.resources.get(type='vm'):
label_values = [resource['id']]
status_metrics.add_metric(label_values, resource['status'] == 'running')
yield status_metrics
示例3: collect
# 需要导入模块: from prometheus_client import core [as 别名]
# 或者: from prometheus_client.core import GaugeMetricFamily [as 别名]
def collect(self):
info = self.rpc.getinfo()
info_labels = {k.replace('-', '_'): v for k, v in info.items() if isinstance(v, str)}
node_info_fam = InfoMetricFamily(
'lightning_node',
'Static node information',
labels=info_labels.keys(),
)
node_info_fam.add_metric(info_labels, info_labels)
yield node_info_fam
blockheight = info['blockheight']
yield GaugeMetricFamily(
'lightning_node_blockheight',
"Current Bitcoin blockheight on this node.",
value=blockheight,
)
fees_msat = info["msatoshi_fees_collected"]
yield GaugeMetricFamily(
'lightning_fees_collected_msat',
'How much have we been paid to route payments?',
value=fees_msat,
)
示例4: parse_rds_performance
# 需要导入模块: from prometheus_client import core [as 别名]
# 或者: from prometheus_client.core import GaugeMetricFamily [as 别名]
def parse_rds_performance(self, id, value):
value_format: str = value['ValueFormat']
metric_name = value['Key']
keys = ['value']
if value_format is not None and '&' in value_format:
keys = value_format.split('&')
metric = value['Values']['PerformanceValue']
if len(metric) < 1:
return
values = metric[0]['Value'].split('&')
for k, v in zip(keys, values):
gauge = GaugeMetricFamily(
self.parent.format_metric_name(rds_performance, metric_name + '_' + k),
'', labels=['instanceId'])
gauge.add_metric([id], float(v))
yield gauge
示例5: collect
# 需要导入模块: from prometheus_client import core [as 别名]
# 或者: from prometheus_client.core import GaugeMetricFamily [as 别名]
def collect(self) -> Iterator[GaugeMetricFamily]:
active, idle, dead = 0, 0, 0
for slave in self._get_slaves():
if slave.is_alive(use_cached=True) and slave.current_build_id is not None:
active += 1
elif slave.is_alive(use_cached=True) and slave.current_build_id is None:
idle += 1
elif not slave.is_alive(use_cached=True) and not slave.is_shutdown():
# Slave is not alive and was not deliberately put in shutdown mode. Count it as dead.
dead += 1
else:
# If not slave.is_alive() and slave.is_shutdown() = True then we have deliberately
# and gracefully killed the slave. We do not want to categorize such a slave as 'dead'
pass
slaves_gauge = GaugeMetricFamily('slaves', 'Total number of slaves', labels=['state'])
slaves_gauge.add_metric(['active'], active)
slaves_gauge.add_metric(['idle'], idle)
slaves_gauge.add_metric(['dead'], dead)
yield slaves_gauge
示例6: collect
# 需要导入模块: from prometheus_client import core [as 别名]
# 或者: from prometheus_client.core import GaugeMetricFamily [as 别名]
def collect(self):
out = urlopen("http://localhost:8500/v1/agent/metrics").read()
metrics = json.loads(out.decode("utf-8"))
for g in metrics["Gauges"]:
yield GaugeMetricFamily(sanitise_name(g["Name"]),
"Consul metric " + g["Name"], g["Value"])
for c in metrics["Counters"]:
yield CounterMetricFamily(sanitise_name(c["Name"]) + "_total",
"Consul metric " + c["Name"], c["Count"])
for s in metrics["Samples"]:
yield SummaryMetricFamily(sanitise_name(s["Name"]) + "_seconds",
"Consul metric " + s["Name"],
count_value=c["Count"], sum_value=s["Sum"] / 1000)
示例7: collect
# 需要导入模块: from prometheus_client import core [as 别名]
# 或者: from prometheus_client.core import GaugeMetricFamily [as 别名]
def collect(self):
commit_metric = GaugeMetricFamily('github_commit_timestamp',
'Commit timestamp', labels=['namespace', 'app', 'image_sha'])
commit_metrics = self.generate_commit_metrics_list(self._namespaces)
for my_metric in commit_metrics:
logging.info("Namespace: %s, App: %s, Build: %s, Timestamp: %s"
% (
my_metric.namespace,
my_metric.name,
my_metric.build_name,
str(float(my_metric.commit_timestamp))
)
)
commit_metric.add_metric([my_metric.namespace, my_metric.name, my_metric.image_hash],
my_metric.commit_timestamp)
yield commit_metric
示例8: collect
# 需要导入模块: from prometheus_client import core [as 别名]
# 或者: from prometheus_client.core import GaugeMetricFamily [as 别名]
def collect(self):
response = requests.get(args.uri)
json = response.json()
metrics = json['metrics']
# iterate over all metrics
for k in metrics:
underscores = re.sub('\.|-|\s', '_', k).lower()
if metrics[k]['type'] == 'timer':
# we have a timer, expose as a Prometheus Summary
underscores = underscores + '_' + metrics[k]['duration_unit']
summary = SummaryMetricFamily(underscores, 'libmedida metric type: ' + metrics[k]['type'], count_value=metrics[k]['count'], sum_value=(metrics[k]['mean'] * metrics[k]['count']))
# add stellar-core calculated quantiles to our summary
summary.add_sample(underscores, labels={'quantile':'0.75'}, value=metrics[k]['75%'])
summary.add_sample(underscores, labels={'quantile':'0.95'}, value=metrics[k]['95%'])
summary.add_sample(underscores, labels={'quantile':'0.99'}, value=metrics[k]['99%'])
yield summary
elif metrics[k]['type'] == 'counter':
# we have a counter, this is a Prometheus Gauge
yield GaugeMetricFamily(underscores, 'libmedida metric type: ' + metrics[k]['type'], value=metrics[k]['count'])
elif metrics[k]['type'] == 'meter':
# we have a meter, this is a Prometheus Counter
yield CounterMetricFamily(underscores, 'libmedida metric type: ' + metrics[k]['type'], value=metrics[k]['count'])
示例9: test_process_metric_filtered
# 需要导入模块: from prometheus_client import core [as 别名]
# 或者: from prometheus_client.core import GaugeMetricFamily [as 别名]
def test_process_metric_filtered(aggregator, mocked_prometheus_check, mocked_prometheus_scraper_config):
""" Metric absent from the metrics_mapper """
filtered_gauge = GaugeMetricFamily(
'process_start_time_seconds', 'Start time of the process since unix epoch in seconds.'
)
filtered_gauge.add_metric([], 123456789.0)
mocked_prometheus_scraper_config['_dry_run'] = False
check = mocked_prometheus_check
check.process_metric(filtered_gauge, mocked_prometheus_scraper_config, metric_transformers={})
check.log.debug.assert_called_with(
'Skipping metric `%s` as it is not defined in the metrics mapper, '
'has no transformer function, nor does it match any wildcards.',
'process_start_time_seconds',
)
aggregator.assert_all_metrics_covered()
示例10: test_submit_gauge_with_labels_and_hostname_already_overridden
# 需要导入模块: from prometheus_client import core [as 别名]
# 或者: from prometheus_client.core import GaugeMetricFamily [as 别名]
def test_submit_gauge_with_labels_and_hostname_already_overridden(
aggregator, mocked_prometheus_check, mocked_prometheus_scraper_config
):
""" submitting metrics that contain labels should result in tags on the gauge call """
ref_gauge = GaugeMetricFamily(
'process_virtual_memory_bytes', 'Virtual memory size in bytes.', labels=['my_1st_label', 'node']
)
ref_gauge.add_metric(['my_1st_label_value', 'foo'], 54927360.0)
check = mocked_prometheus_check
mocked_prometheus_scraper_config['label_to_hostname'] = 'node'
metric_name = mocked_prometheus_scraper_config['metrics_mapper'][ref_gauge.name]
check.submit_openmetric(metric_name, ref_gauge, mocked_prometheus_scraper_config, hostname='bar')
aggregator.assert_metric(
'prometheus.process.vm.bytes',
54927360.0,
tags=['my_1st_label:my_1st_label_value', 'node:foo'],
hostname="bar",
count=1,
)
示例11: test_submit_gauge_with_labels_mapper
# 需要导入模块: from prometheus_client import core [as 别名]
# 或者: from prometheus_client.core import GaugeMetricFamily [as 别名]
def test_submit_gauge_with_labels_mapper(aggregator, mocked_prometheus_check, mocked_prometheus_scraper_config):
"""
Submitting metrics that contain labels mappers should result in tags
on the gauge call with transformed tag names
"""
ref_gauge = GaugeMetricFamily(
'process_virtual_memory_bytes', 'Virtual memory size in bytes.', labels=['my_1st_label', 'my_2nd_label']
)
ref_gauge.add_metric(['my_1st_label_value', 'my_2nd_label_value'], 54927360.0)
check = mocked_prometheus_check
mocked_prometheus_scraper_config['labels_mapper'] = {
'my_1st_label': 'transformed_1st',
'non_existent': 'should_not_matter',
'env': 'dont_touch_custom_tags',
}
mocked_prometheus_scraper_config['custom_tags'] = ['env:dev', 'app:my_pretty_app']
metric = mocked_prometheus_scraper_config['metrics_mapper'][ref_gauge.name]
check.submit_openmetric(metric, ref_gauge, mocked_prometheus_scraper_config)
aggregator.assert_metric(
'prometheus.process.vm.bytes',
54927360.0,
tags=['env:dev', 'app:my_pretty_app', 'transformed_1st:my_1st_label_value', 'my_2nd_label:my_2nd_label_value'],
count=1,
)
示例12: collect_host_capacity_statistics
# 需要导入模块: from prometheus_client import core [as 别名]
# 或者: from prometheus_client.core import GaugeMetricFamily [as 别名]
def collect_host_capacity_statistics():
default_zstack_path = '/usr/local/zstack/apache-tomcat/webapps/zstack'
zstack_env_path = os.environ.get('ZSTACK_HOME', None)
if zstack_env_path and zstack_env_path != default_zstack_path:
default_zstack_path = zstack_env_path
zstack_dir = ['/var/lib/zstack', '%s/../../../' % default_zstack_path, '/opt/zstack-dvd/',
'/var/log/zstack', '/var/lib/mysql', '/var/lib/libvirt', '/tmp/zstack']
metrics = {
'zstack_used_capacity_in_bytes': GaugeMetricFamily('zstack_used_capacity_in_bytes',
'ZStack used capacity in bytes')
}
zstack_used_capacity = 0
for dir in zstack_dir:
if not os.path.exists(dir):
continue
cmd = "du -bs %s | awk {\'print $1\'}" % dir
res = bash_o(cmd)
zstack_used_capacity += int(res)
metrics['zstack_used_capacity_in_bytes'].add_metric([], float(zstack_used_capacity))
return metrics.values()
示例13: collect_lvm_capacity_statistics
# 需要导入模块: from prometheus_client import core [as 别名]
# 或者: from prometheus_client.core import GaugeMetricFamily [as 别名]
def collect_lvm_capacity_statistics():
metrics = {
'vg_size': GaugeMetricFamily('vg_size',
'volume group size', None, ['vg_name']),
'vg_avail': GaugeMetricFamily('vg_avail',
'volume group and thin pool free size', None, ['vg_name']),
}
r, o, e = bash_roe("vgs --nolocking --noheading -oname")
if r != 0 or len(o.splitlines()) == 0:
return metrics.values()
vg_names = o.splitlines()
for name in vg_names:
name = name.strip()
size, avail = lvm.get_vg_size(name, False)
metrics['vg_size'].add_metric([name], float(size))
metrics['vg_avail'].add_metric([name], float(avail))
return metrics.values()
示例14: _add_metrics
# 需要导入模块: from prometheus_client import core [as 别名]
# 或者: from prometheus_client.core import GaugeMetricFamily [as 别名]
def _add_metrics(self, metrics, metric_name, metric_gauges, data):
metric_id = re.sub('(\.)', '_', metrics['id']).lower()
metric_id = re.sub('(\+)', '_plus_', metric_id)
metric_value = self._dot_get(metrics['id'], data)
gauges = [metric_id]
for gauge in metric_gauges:
gauges.append(gauge)
if metric_value is not False:
if isinstance(metric_value, list):
metric_value = sum(metric_value) / float(len(metric_value))
if not metric_id in self.gauges:
self.gauges[metric_id] = GaugeMetricFamily('%s_%s' % (metric_name, metric_id), '%s' % metric_id, value=None, labels=metrics['labels'])
self.gauges[metric_id].add_metric(gauges, value=metric_value)
示例15: collect
# 需要导入模块: from prometheus_client import core [as 别名]
# 或者: from prometheus_client.core import GaugeMetricFamily [as 别名]
def collect(self):
config = self._config
result = json.loads(urllib2.urlopen(config['json_data_url'], timeout=10).read())
result_tree = Tree(result)
for metric_config in config['metrics']:
metric_name = "{}_{}".format(config['metric_name_prefix'], metric_config['name'])
metric_description = metric_config.get('description', '')
metric_path = metric_config['path']
value = result_tree.execute(metric_path)
logging.debug("metric_name: {}, value for '{}' : {}".format(metric_name, metric_path, value))
metric = GaugeMetricFamily(metric_name, metric_description, value=value)
yield metric