【问题标题】:How to push metrics with Python and Prometheus Pushgateway如何使用 Python 和 Prometheus Pushgateway 推送指标
【发布时间】:2016-12-06 07:11:42
【问题描述】:

我希望使用 Pushgateway 将多标签指标推送到 Prometheus。该文档提供了一个 curl 示例,但我需要通过 Python 发送它。另外,我想在指标中嵌入多个标签。

【问题讨论】:

    标签: python prometheus prometheus-pushgateway


    【解决方案1】:

    这就是我最终做的事情 - 花了一段时间才弄好。虽然理想情况下我会使用专门为此目的设计的 Prometheus python 客户端,但它似乎在某些情况下不支持多个标签,并且文档几乎不存在 - 所以我选择了一个自制的解决方案。

    以下代码使用 gevent 并支持多个(逗号分隔)pushgateway url(如“pushgateway1.my.com:9092, pushgateway2.my.com:9092”)。

    import gevent
    import requests
    
    def _submit_wrapper(urls, job_name, metric_name, metric_value, dimensions):
        dim = ''
        headers = {'X-Requested-With': 'Python requests', 'Content-type': 'text/xml'}
        for key, value in dimensions.iteritems():
            dim += '/%s/%s' % (key, value)
        for url in urls:
            requests.post('http://%s/metrics/job/%s%s' % (url, job_name, dim),
                          data='%s %s\n' % (metric_name, metric_value), headers=headers)
    
    
    def submit_metrics(job_name, metric_name, metric_value, dimensions={}):
        from ..app import config
        cfg = config.init()
        urls = cfg['PUSHGATEWAY_URLS'].split(',')
        gevent.spawn(_submit_wrapper, urls, job_name, metric_name, metric_value, dimensions)
    

    【讨论】:

    • 上面的代码生成了一个无类型的指标。要生成类型化指标,您需要在负载前添加“# TYPE counter\n”(对于计数器指标)。
    【解决方案2】:

    【讨论】:

      【解决方案3】:

      第一步:安装客户端:

      pip install prometheus_client
      

      第二步:将以下内容粘贴到 Python 解释器中:

      from prometheus_client import CollectorRegistry, Gauge, push_to_gateway
      
      registry = CollectorRegistry()
      g = Gauge('job_last_success_unixtime', 'Last time a batch job successfully finished', registry=registry)
      g.set_to_current_time()
      push_to_gateway('localhost:9091', job='batchA', registry=registry)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多