Python prometheus_client.REGISTRY Examples

The following are 14 code examples of prometheus_client.REGISTRY(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module prometheus_client , or try the search function .
Example #1
Source File: testutils.py    From django-prometheus with Apache License 2.0 5 votes vote down vote up
def saveRegistry(self, registry=REGISTRY):
        """Freezes a registry. This lets a user test changes to a metric
        instead of testing the absolute value. A typical use case looks like:

          registry = self.saveRegistry()
          doStuff()
          self.assertMetricDiff(registry, 1, 'stuff_done_total')
        """
        return copy.deepcopy(list(registry.collect())) 
Example #2
Source File: testutils.py    From django-prometheus with Apache License 2.0 5 votes vote down vote up
def getMetric(self, metric_name, registry=REGISTRY, **labels):
        """Gets a single metric."""
        return self.getMetricFromFrozenRegistry(
            metric_name, registry.collect(), **labels
        ) 
Example #3
Source File: testutils.py    From django-prometheus with Apache License 2.0 5 votes vote down vote up
def getMetricVector(self, metric_name, registry=REGISTRY):
        """Returns the values for all labels of a given metric.

        The result is returned as a list of (labels, value) tuples,
        where `labels` is a dict.

        This is quite a hack since it relies on the internal
        representation of the prometheus_client, and it should
        probably be provided as a function there instead.
        """
        return self.getMetricVectorFromFrozenRegistry(metric_name, registry.collect()) 
Example #4
Source File: testutils.py    From django-prometheus with Apache License 2.0 5 votes vote down vote up
def assertMetricEquals(
        self, expected_value, metric_name, registry=REGISTRY, **labels
    ):
        """Asserts that metric_name{**labels} == expected_value."""
        value = self.getMetric(metric_name, registry=registry, **labels)
        self.assertEqual(
            expected_value,
            value,
            METRIC_EQUALS_ERR_EXPLANATION
            % (
                metric_name,
                self.formatLabels(labels),
                value,
                expected_value,
                metric_name,
                self.formatVector(self.getMetricVector(metric_name)),
            ),
        ) 
Example #5
Source File: testutils.py    From django-prometheus with Apache License 2.0 5 votes vote down vote up
def assertMetricDiff(
        self, frozen_registry, expected_diff, metric_name, registry=REGISTRY, **labels
    ):
        """Asserts that metric_name{**labels} changed by expected_diff between
        the frozen registry and now. A frozen registry can be obtained
        by calling saveRegistry, typically at the beginning of a test
        case.
        """
        saved_value = self.getMetricFromFrozenRegistry(
            metric_name, frozen_registry, **labels
        )
        current_value = self.getMetric(metric_name, registry=registry, **labels)
        self.assertFalse(
            current_value is None,
            METRIC_DIFF_ERR_NONE_EXPLANATION
            % (metric_name, self.formatLabels(labels), saved_value, current_value),
        )
        diff = current_value - (saved_value or 0.0)
        self.assertEqual(
            expected_diff,
            diff,
            METRIC_DIFF_ERR_EXPLANATION
            % (
                metric_name,
                self.formatLabels(labels),
                diff,
                expected_diff,
                saved_value,
                current_value,
            ),
        ) 
Example #6
Source File: exports.py    From django-prometheus with Apache License 2.0 5 votes vote down vote up
def ExportToDjangoView(request):
    """Exports /metrics as a Django view.

    You can use django_prometheus.urls to map /metrics to this view.
    """
    if "prometheus_multiproc_dir" in os.environ:
        registry = prometheus_client.CollectorRegistry()
        multiprocess.MultiProcessCollector(registry)
    else:
        registry = prometheus_client.REGISTRY
    metrics_page = prometheus_client.generate_latest(registry)
    return HttpResponse(
        metrics_page, content_type=prometheus_client.CONTENT_TYPE_LATEST
    ) 
Example #7
Source File: web.py    From prometheus-async with Apache License 2.0 5 votes vote down vote up
def server_stats(request):
    """
    Return a web response with the plain text version of the metrics.

    :rtype: :class:`aiohttp.web.Response`
    """
    rsp = web.Response(body=generate_latest(REGISTRY))
    # This is set separately because aiohttp complains about `;` in
    # content_type thinking it means there's also a charset.
    # cf. https://github.com/aio-libs/aiohttp/issues/2197
    rsp.content_type = CONTENT_TYPE_LATEST
    return rsp 
Example #8
Source File: test_example.py    From prometheus_flask_exporter with MIT License 5 votes vote down vote up
def app() -> Flask:
    app = create_app('myapp.config.TestConfig')
    prometheus_client.REGISTRY = prometheus_client.CollectorRegistry(auto_describe=True)
    myapp_extensions.metrics = GunicornInternalPrometheusMetrics.for_app_factory(group_by="endpoint")
    ctx = app.app_context()
    ctx.push()
    yield app
    ctx.pop() 
Example #9
Source File: unittest_helper.py    From prometheus_flask_exporter with MIT License 5 votes vote down vote up
def setUp(self):
        self.app = Flask(__name__)
        self.app.testing = True
        self.client = self.app.test_client()

        # reset the underlying Prometheus registry
        prometheus_client.REGISTRY = prometheus_client.CollectorRegistry(auto_describe=True) 
Example #10
Source File: metrics.py    From binderhub with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get(self):
        self.set_header("Content-Type", CONTENT_TYPE_LATEST)
        self.write(generate_latest(REGISTRY)) 
Example #11
Source File: prometheus.py    From quay with Apache License 2.0 5 votes vote down vote up
def run(self):
        agg_url = self._app.config.get("PROMETHEUS_PUSHGATEWAY_URL")
        while True:
            # Practically disable this worker, if there is no pushgateway.
            if agg_url is None or os.getenv("TEST", "false").lower() == "true":
                time.sleep(ONE_DAY_IN_SECONDS)
                continue

            time.sleep(PROMETHEUS_PUSH_INTERVAL_SECONDS)
            try:
                push_to_gateway(
                    agg_url,
                    job=self._app.config.get("PROMETHEUS_NAMESPACE", "quay"),
                    registry=REGISTRY,
                    grouping_key=process_grouping_key(),
                )
                logger.debug(
                    "pushed registry to pushgateway at %s with grouping key %s",
                    agg_url,
                    process_grouping_key(),
                )
            except urllib.error.URLError:
                # There are many scenarios when the gateway might not be running.
                # These could be testing scenarios or simply processes racing to start.
                # Rather than try to guess all of them, keep it simple and let it fail.
                if os.getenv("DEBUGLOG", "false").lower() == "true":
                    logger.exception(
                        "failed to push registry to pushgateway at %s with grouping key %s",
                        agg_url,
                        process_grouping_key(),
                    )
                else:
                    pass 
Example #12
Source File: cloud_region.py    From openstacksdk with Apache License 2.0 5 votes vote down vote up
def get_prometheus_registry(self):
        if not self._collector_registry and prometheus_client:
            self._collector_registry = prometheus_client.REGISTRY
        return self._collector_registry 
Example #13
Source File: app.py    From biggraphite with Apache License 2.0 5 votes vote down vote up
def __init__(self, registry=None):
        """Constructor."""
        registry = registry or prometheus_client.REGISTRY
        # Here registry is explicit to allow us to mess with it in the tests.
        self.gourde = gourde.Gourde(__name__, registry=registry)
        self.app = self.gourde.app
        self.accessor = None
        self.args = None 
Example #14
Source File: core.py    From zabbix-exporter with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def do_GET(self):
        try:
            scrapes_total.inc()
            response = generate_latest(REGISTRY) + generate_latest(exporter_registry)
            status = 200
        except Exception:
            logger.exception('Fetch failed')
            response = ''
            status = 500
        self.send_response(status)
        self.send_header('Content-Type', CONTENT_TYPE_LATEST)
        self.end_headers()
        self.wfile.write(response)