Python prometheus_client.CONTENT_TYPE_LATEST Examples

The following are 14 code examples of prometheus_client.CONTENT_TYPE_LATEST(). 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: view.py    From starlette-prometheus with GNU General Public License v3.0 5 votes vote down vote up
def metrics(request: Request) -> Response:
    if "prometheus_multiproc_dir" in os.environ:
        registry = CollectorRegistry()
        MultiProcessCollector(registry)
    else:
        registry = REGISTRY

    return Response(generate_latest(registry), media_type=CONTENT_TYPE_LATEST) 
Example #2
Source File: yourapp.py    From prometheus-multiprocessing-example with ISC License 5 votes vote down vote up
def metrics():
    registry = CollectorRegistry()
    multiprocess.MultiProcessCollector(registry)
    data = generate_latest(registry)
    return Response(data, mimetype=CONTENT_TYPE_LATEST) 
Example #3
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 #4
Source File: __init__.py    From prometheus_flask_exporter with MIT License 5 votes vote down vote up
def register_endpoint(self, path, app=None):
        """
        Register the metrics endpoint on the Flask application.

        :param path: the path of the endpoint
        :param app: the Flask application to register the endpoint on
            (by default it is the application registered with this class)
        """

        if is_running_from_reloader() and not os.environ.get('DEBUG_METRICS'):
            return

        if app is None:
            app = self.app or current_app

        @app.route(path)
        @self.do_not_track()
        def prometheus_metrics():
            # import these here so they don't clash with our own multiprocess module
            from prometheus_client import multiprocess, CollectorRegistry

            if 'prometheus_multiproc_dir' in os.environ:
                registry = CollectorRegistry()
            else:
                registry = self.registry

            if 'name[]' in request.args:
                registry = registry.restricted_registry(request.args.getlist('name[]'))

            if 'prometheus_multiproc_dir' in os.environ:
                multiprocess.MultiProcessCollector(registry)

            headers = {'Content-Type': CONTENT_TYPE_LATEST}
            return generate_latest(registry), 200, headers 
Example #5
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 #6
Source File: prometheus.py    From zentral with Apache License 2.0 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        bearer_token = settings['apps']['zentral.contrib.inventory'].get('prometheus_bearer_token')
        if bearer_token and request.META.get('HTTP_AUTHORIZATION') == "Bearer {}".format(bearer_token):
            content = ""
            registry = self.get_registry()
            if registry is not None:
                content = generate_latest(registry)
            return HttpResponse(content, content_type=CONTENT_TYPE_LATEST)
        else:
            return HttpResponseForbidden() 
Example #7
Source File: prometheus_openstack_exporter.py    From prometheus-openstack-exporter with GNU General Public License v3.0 5 votes vote down vote up
def do_GET(self):
        url = urlparse.urlparse(self.path)
        if url.path == '/metrics':
            try:
                collectors = [COLLECTORS[collector]() for collector in get_collectors(config.get('enabled_collectors'))]
                log.debug("Collecting stats..")
                output = ''
                for collector in collectors:
                    output += collector.get_stats()
                if data_gatherer:
                    output += data_gatherer.get_stats()

                self.send_response(200)
                self.send_header('Content-Type', CONTENT_TYPE_LATEST)
                self.end_headers()
                self.wfile.write(output)
            except Exception:
                self.send_response(500)
                self.end_headers()
                self.wfile.write(traceback.format_exc())
        elif url.path == '/':
            self.send_response(200)
            self.end_headers()
            self.wfile.write("""<html>
            <head><title>OpenStack Exporter</title></head>
            <body>
            <h1>OpenStack Exporter</h1>
            <p>Visit <code>/metrics</code> to use.</p>
            </body>
            </html>""")
        else:
            self.send_response(404)
            self.end_headers() 
Example #8
Source File: views.py    From promgen with MIT License 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        return HttpResponse(
            prometheus_client.generate_latest(self.registry),
            content_type=prometheus_client.CONTENT_TYPE_LATEST,
        ) 
Example #9
Source File: prom_client.py    From faucet with Apache License 2.0 5 votes vote down vote up
def make_wsgi_app(registry):
    """Create a WSGI app which serves the metrics from a registry."""

    def prometheus_app(environ, start_response):
        query_str = environ.get('QUERY_STRING', '')
        params = parse_qs(query_str)
        reg = registry
        if 'name[]' in params:
            reg = reg.restricted_registry(params['name[]'])
        output = generate_latest(reg)
        status = str('200 OK')
        headers = [(str('Content-type'), CONTENT_TYPE_LATEST)]
        start_response(status, headers)
        return [output]
    return prometheus_app 
Example #10
Source File: prometheus_app.py    From postgraas_server with Apache License 2.0 5 votes vote down vote up
def metrics():
    try:
        content = generate_latest(REGISTRY)
        return content, 200, {'Content-Type': CONTENT_TYPE_LATEST}
    except Exception as error:
        logging.exception("Any exception occured during scraping")
        abort(Response("Scrape failed: {}".format(error), status=502)) 
Example #11
Source File: main.py    From prometheus-openstack-exporter with Apache License 2.0 5 votes vote down vote up
def do_GET(self):
        url = urlparse.urlparse(self.path)
        if url.path == '/metrics':
            output = ''
            for collector in collectors:
                try:
                    stats = collector.get_stats()
                    if stats is not None:
                        output = output + stats
                except BaseException:
                    logger.warning(
                        "Could not get stats for collector {}".format(
                            collector.get_cache_key()))
            self.send_response(200)
            self.send_header('Content-Type', CONTENT_TYPE_LATEST)
            self.end_headers()
            self.wfile.write(output)
        elif url.path == '/':
            self.send_response(200)
            self.end_headers()
            self.wfile.write("""<html>
            <head><title>OpenStack Exporter</title></head>
            <body>
            <h1>OpenStack Exporter</h1>
            <p>Visit <code>/metrics</code> to use.</p>
            </body>
            </html>""")
        else:
            self.send_response(404)
            self.end_headers() 
Example #12
Source File: views.py    From azure-cost-mon with MIT License 5 votes vote down vote up
def metrics():
    registry = CollectorRegistry()
    _register_collectors(registry)

    try:
        content = generate_latest(registry)
        return content, 200, {'Content-Type': CONTENT_TYPE_LATEST}
    except Exception as e:
        abort(Response("Scrape failed: {}".format(e), status=502)) 
Example #13
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) 
Example #14
Source File: metrics.py    From taranis with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get(self):
        return Response(prometheus_client.generate_latest(), mimetype=prometheus_client.CONTENT_TYPE_LATEST)