当前位置: 首页>>代码示例>>Python>>正文


Python prometheus_client.Gauge类代码示例

本文整理汇总了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)
开发者ID:cloudcomputinghust,项目名称:IoT,代码行数:28,代码来源:prometheus_export.py

示例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)
开发者ID:lyandut,项目名称:st2,代码行数:7,代码来源:prometheus_driver.py

示例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)
开发者ID:lyandut,项目名称:st2,代码行数:7,代码来源:prometheus_driver.py

示例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)
开发者ID:jeevadotnet,项目名称:prometheus-openstack-exporter,代码行数:9,代码来源:oscache.py

示例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)
开发者ID:elfchief,项目名称:calico,代码行数:10,代码来源:futils.py

示例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)
开发者ID:bendikwa,项目名称:temperature_exporter,代码行数:11,代码来源:temp.py

示例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)
开发者ID:turtlemonvh,项目名称:prometheus_python_roller,代码行数:54,代码来源:roller.py

示例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)
开发者ID:pkarkazis,项目名称:son-monitor,代码行数:12,代码来源:prompw.py

示例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)
开发者ID:spotify,项目名称:luigi,代码行数:59,代码来源:prometheus_metric.py

示例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
开发者ID:turtlemonvh,项目名称:prometheus_python_roller,代码行数:27,代码来源:roller.py

示例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
     )
开发者ID:spotify,项目名称:luigi,代码行数:33,代码来源:prometheus_metric.py

示例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)
开发者ID:jeevadotnet,项目名称:prometheus-openstack-exporter,代码行数:17,代码来源:nova_services.py

示例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)
开发者ID:jeevadotnet,项目名称:prometheus-openstack-exporter,代码行数:17,代码来源:hypervisor_stats.py

示例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)
开发者ID:fgeller,项目名称:prometheus-mysql-exporter,代码行数:34,代码来源:__init__.py

示例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)
开发者ID:turtlemonvh,项目名称:prometheus_python_roller,代码行数:45,代码来源:roller.py


注:本文中的prometheus_client.Gauge类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。