🌐
client_python
prometheus.github.io › client_python
client_python
This tutorial shows the quickest way to get started with the Prometheus Python library. ... from prometheus_client import start_http_server, Summary import random import time # Create a metric to track time spent and requests made. REQUEST_TIME = Summary('request_processing_seconds', 'Time ...
Discussions

python - Expose package metrics to Prometheus with prometheus_client - Stack Overflow
Expose the metrics from your client using an HTTP server|endpoint · Configure the Prometheus server to target this metric server|endpoint · If you run the Three Step Demo example on the page that you reference, and then browse http://localhost:8000, you should see something like: # HELP python_g... More on stackoverflow.com
🌐 stackoverflow.com
What is the official way of monitoring web backend applications?
The problem is you're stuck in a bit of an old-school way of thinking. The standard Prometheus client libraries are well supported, secure, and scaleable. Remember, there's more to getting metrics out of systems than just spewing data. There's monitoring and observability theory as well. The reaoson Prometheus is a polling based system is that it's more than just metrics. It's monitoring. You get active health check polling as part of the protocol. Every scrape includes automatic health related metrics . Prometheus has a huge list of dynamic discovery options , including interfaces where you can add your own discovery. It looks very invasive to me and raises a red flag as a security issue. Again old-school way of thinking. Why is this a red flag? Services exposes various APIs, Prometheus metrics are just one more kind of API. You can put it inline on your main API port and protect it with firewall rules, reverse proxy rules, etc. Or you can put it on a separate port, where you also can include things like /healthy and /ready endpoints and other things used for orchestration health checks. This is what we do, we have a standard internal health endpoint where you can access metrics, profiles, etc. My backend servers are also in an autoscaling environment where they are started and stopped in a non-predictable time. And they are all behind some security network layers only accessible on ports 80/443 through some HTTP balancing node. Prometheus is intended to sit inside your network, behind the security perimiter, behind your load-balancing. Prometheus is a monitoring system, it needs to watch the health. It's not a SaaS, you run it inside your network. My question is, how this is done in reality? You have your backend application and want to send some telemetry data to Prometheus. What is the way to do it? We run all of our services on Kubernetes and monitor with the Prometheus Operator . The Operator allows services to self-register themselves, usually via the PodMonitor object. As above, our metrics are on a separate port not defined in the Service or Ingress, so they're inaccessible outside of the cluster. The Prometheus instanances live inside our Kubernetes cluster, monitoring everything from the cluster itself, the applications, cron jobs, importing data from CloudWatch, you name it. More on reddit.com
🌐 r/PrometheusMonitoring
26
0
May 9, 2024
Defining the metrics path in Python client.
I'm not a python expert, but the simplest way for me would be to create a Flask app. https://prometheus.github.io/client_python/exporting/http/flask/ More on reddit.com
🌐 r/PrometheusMonitoring
2
2
June 26, 2024
Setting labels in Histogram observe function.
No, observes are one-time only. Usually what you do for tasks entering/leaving like this is to have two metrics. A simple counter that is incremented at thestart. So you know how many tasks have been added. A histogram that is only "observed" at the end, with a label for the final state. More on reddit.com
🌐 r/PrometheusMonitoring
2
1
January 22, 2024
🌐
Prometheus
prometheus.io › docs › instrumenting › clientlibs
Client libraries | Prometheus
Choose a Prometheus client library that matches the language in which your application is written. This lets you define and expose internal metrics via an HTTP endpoint on your application’s instance: Go · Java or Scala · Python · Ruby · Rust · Unofficial third-party client libraries: Bash ·
🌐
GitHub
github.com › Lispython › prometheus_client_example
GitHub - Lispython/prometheus_client_example: Python prometheus client usage examples
Python prometheus client usage examples. Contribute to Lispython/prometheus_client_example development by creating an account on GitHub.
Author: Lispython
🌐
GitHub
github.com › steve-caron-grafana › prometheus-examples › blob › main › clients › python › README.md
prometheus-examples/clients/python/README.md at main · steve-caron-grafana/prometheus-examples
To scrape the metrics, add a job in your Prometheus or Grafana agent config, for example: scrape_configs: - job_name: custom-metrics-python static_configs: - targets: ['localhost:8000'] labels: process: 'simple-python-client.py'
Author: steve-caron-grafana
🌐
PyPI
pypi.org › project › prometheus-client
prometheus-client · PyPI
Details for the file prometheus_client-0.25.0.tar.gz. ... See more details on using hashes here. Details for the file prometheus_client-0.25.0-py3-none-any.whl.
      » pip install prometheus-client
    
Published: Apr 09, 2026
Version: 0.25.0
🌐
GitHub
github.com › valohai › prometheus-client-python
GitHub - valohai/prometheus-client-python: Prometheus instrumentation library for Python applications · GitHub
The client also automatically exports some metadata about Python. If using Jython, metadata about the JVM in use is also included. This information is available as labels on the python_info metric. The value of the metric is 1, since it is the labels that carry information. There are several options for exporting metrics. Metrics are usually exposed over HTTP, to be read by the Prometheus server.
Author: valohai
Top answer
1 of 1
7

Prometheus server scrapes HTTP endpoints that provide metrics. This differs from some other metric systems where the metrics are pushed to the metric system. Because Prometheus scrapes metric endpoints, you need to do two things:

  1. Expose the metrics from your client using an HTTP server|endpoint
  2. Configure the Prometheus server to target this metric server|endpoint

If you run the Three Step Demo example on the page that you reference, and then browse http://localhost:8000, you should see something like:

# HELP python_gc_objects_collected_total Objects collected during gc
# TYPE python_gc_objects_collected_total counter
python_gc_objects_collected_total{generation="0"} 357.0
python_gc_objects_collected_total{generation="1"} 0.0
python_gc_objects_collected_total{generation="2"} 0.0
...
...
# HELP request_processing_seconds Time spent processing request
# TYPE request_processing_seconds summary
request_processing_seconds_count 4.0
request_processing_seconds_sum 2.0374009040533565
# HELP request_processing_seconds_created Time spent processing request
# TYPE request_processing_seconds_created gauge
request_processing_seconds_created 1.6004497426536365e+09

This is the page that your Prometheus server would be configured to scrape. You can see, e.g. python_gc_objects_collected_total counter is provided. Prometheus metrics are human readable which is useful.

If you combine, your sandbox1.py into this example:

from prometheus_client import start_http_server, Counter, Summary
import random
import time

# Create a metric to track time spent and requests made.
REQUEST_TIME = Summary('request_processing_seconds',
                       'Time spent processing request')


# Decorate function with metric.
@REQUEST_TIME.time()
def process_request(t):
    """A dummy function that takes some time."""
    time.sleep(t)


if __name__ == '__main__':
    my_counter1 = Counter('my_counter1', 'My counter')
    # Start up the server to expose the metrics.
    start_http_server(8000)
    # Generate some requests.
    while True:
        my_counter1.inc()
        process_request(random.random())

And run the code again, you should now see:

# HELP python_gc_objects_collected_total Objects collected during gc
# TYPE python_gc_objects_collected_total counter
python_gc_objects_collected_total{generation="0"} 357.0
python_gc_objects_collected_total{generation="1"} 0.0
python_gc_objects_collected_total{generation="2"} 0.0
...
...
# HELP my_counter1_total My counter
# TYPE my_counter1_total counter
my_counter1_total 13.0
# HELP my_counter1_created My counter
# TYPE my_counter1_created gauge
my_counter1_created 1.6004498408280134e+09

NOTE At the bottom of the page is my_counter1_total and my_counter1_created which correspond to your my_counter1 = Counter("my_counter1","My counter")

If you point a Prometheus server at this target (localhost:8000), you should be able to e.g. graph the my_counter1_total counter and the my_counter1_created gauge.

Create a file called prometheus.yml:

global:
  scrape_interval: 15s
  evaluation_interval: 15s

scrape_configs:
  # Self
  - job_name: "prometheus-server"
    static_configs:
      - targets:
          - "localhost:9090"

  # Python example
  - job_name: "63957470"
    static_configs:
      - targets:
          - "localhost:8000"

And then run Prometheus:

docker run \
--interactive --tty \
--net=host \
--volume=${PWD}/prometheus.yml:/etc/prometheus/prometheus.yml \
prom/prometheus@sha256:f3ada803723ccbc443ebea19f7ab24d3323def496e222134bf9ed54ae5b787bd

NOTE This assumes that prometheus.yml is in the working directory

The, you can browse Prometheus on http://localhost:9090

You can see your code configured as a target: http://localhost:9090/targets

And you can query|graph your metrics. Type e.g. my_counter1_ to see both and then my_counter1_total for the Counter:

Find elsewhere
🌐
Better Stack
betterstack.com › community › guides › monitoring › prometheus-python-metrics
Python Monitoring with Prometheus (Beginner's Guide) | Better Stack Community
February 17, 2025 - Before starting the services, rename .env.example to .env. This file contains the application's PORT setting: ... [+] Running 3/3 ✔ Network prometheus-python_default Created 0.8s ✔ Container prometheus Started 1.3s ✔ Container app Started 1.3s
🌐
Medium
medium.com › @dast04 › writing-custom-prometheus-exporters-in-python-kubernetes-73626b66d78c
Writing Custom Prometheus Exporters (in Python) — Kubernetes | by Daniello | Medium
August 22, 2024 - Note: Remember to createrequirements.txt file with necessary Python dependencies, in this case: prometheus-client ... import random import time from prometheus_client import start_http_server, Gauge # Create a Prometheus gauge metric random_number_metric = Gauge('random_number', 'Random number generated every 30 sec') def generate_random_number(): # Generate a random number between 1 and 10 return random.randint(1, 10) if __name__ == '__main__': # Start the Prometheus HTTP server on port 8000 start_http_server(8000) while True: # Generate a random number random_number = generate_random_number() print('Random number is: ', random_number) # Set the value of the Prometheus metric random_number_metric.set(random_number) # Sleep for 30 sec time.sleep(30)
🌐
CloudBees
cloudbees.com › blog › monitoring-your-synchronous-python-web-applications-using-prometheus
Monitoring Your Synchronous Python Web Applications Using Prometheus
June 5, 2026 - For example request_count{http_status="500"} will only show the requests that were unsuccessful with a 500 HTTP status code. To learn more about querying Prometheus, see the querying Prometheus documentation.
🌐
Medium
medium.com › @simrankumari1344 › setting-up-prometheus-server-with-a-python-app-a-step-by-step-guide-fadba7d35dbe
Setting Up Prometheus Server with a Python App: A Step-by-Step Guide | by Simran Kumari | Medium
January 13, 2025 - By the end, you’ll have a working example to visualize metrics and explore Prometheus’s capabilities. The first step is to create a dummy Python app that Prometheus will scrape for metrics. Here’s how to get started: Install Prometheus Client Library Use the prometheus_client library ...
🌐
DBI Services
dbi-services.com › accueil › instrument your python application with prometheus (part1)
Instrument your python application with Prometheus (Part1)
July 10, 2023 - from flask import Flask, jsonify, request, render_template, redirect, url_for from prometheus_client import Counter REQUESTS = Counter('http_request_total', 'Total number of requests') app = Flask(__name__) (...)
🌐
Readthedocs
prometheus-api-client-python.readthedocs.io › en › latest › source › prometheus_api_client.html
prometheus_api_client package — Prometheus Client API Python 0.0.1 documentation
Example: {“Authorization”: “bearer my_oauth_token_to_the_host”} disable_ssl – (bool) If set to True, will disable ssl certificate verification for the http requests made to the prometheus host · retry – (Retry) Retry adapter to retry on HTTP errors · auth – (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth. See python ...
🌐
Medium
medium.com › @letathenasleep › exposing-python-metrics-with-prometheus-c5c837c21e4d
Exposing Python Metrics with Prometheus | by Adso | Medium | Medium
July 6, 2023 - First, let’s create a Python API app using Flask. Create a new directory for your project and navigate to it. Then, create a file named app.py with the following code: from flask import Flask, jsonify, request from prometheus_client import make_wsgi_app, Counter, Histogram from werkzeug.middleware.dispatcher import DispatcherMiddleware import timeapp = Flask(__name__)app.wsgi_app = DispatcherMiddleware(app.wsgi_app, { '/metrics': make_wsgi_app() })REQUEST_COUNT = Counter( 'app_request_count', 'Application Request Count', ['method', 'endpoint', 'http_status'] )REQUEST_LATENCY = Histogram( 'ap
🌐
Google Groups
groups.google.com › g › prometheus-users › c › 1dtFMQH0fRs
Prometheus Python Client - How to collect only on scrape and control targets?
January 2, 2022 - It also serves as a simple example of how to write a custom endpoint." ... Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message ... Thank you sir for that guidance. Tested the callback function approach and that seems to be simple and fits the use case well. This seems to work: from prometheus_client import start_http_server, Gauge import random import time g = Gauge('some_test_metric', 'TEST METRIC') def test_gauge(): x = random.random() print(x) return(x) g.set_function(lambda: test_gauge()) if __name__ == '__main__': # Start up the server to expose the metrics.
🌐
DEV Community
dev.to › leapcell › understanding-prometheus-and-monitoring-python-applications-3d0p
Understanding Prometheus and Monitoring Python Applications - DEV Community
May 28, 2025 - This article will delve into Prometheus data types, provide Python code examples to demonstrate their usage, analyze how they change over time (within one minute and five minutes), explain the underlying change principles, and finally present a Prometheus flowchart using English bash box diagrams.
🌐
Prometheus
prometheus.io › docs › instrumenting › writing_clientlibs
Writing client libraries | Prometheus
For example, the CollectorRegistry.get_sample_value in Python. Ideally, a client library can be included in any application to add some instrumentation without breaking the application. Accordingly, caution is advised when adding dependencies to the client library. For example, if you add a library that uses a Prometheus ...
🌐
PyPI
pypi.org › project › prometheus
prometheus · PyPI
For example this example without const labels ```python ram_metric = Gauge("memory_usage_bytes", "Memory usage in bytes.") ram_metric.set({'type': "virtual", 'host': host}, 100) ram_metric.set({'type': "swap", 'host': host}, 100) ``` is the same as this one with const labels: ```python ram_metric = Gauge("memory_usage_bytes", "Memory usage in bytes.", {'host': host}) ram_metric.set({'type': "virtual", }, 100) ram_metric.set({'type': "swap", }, 100) ``` Examples -------- ### Serve examples #### Gauges * [Memory and cpu usage](examples/memory_cpu_usage_example.py) (Requires psutil) * [Trigonomet
🌐
Generalist Programmer
generalistprogrammer.com › home › tutorials › python packages › prometheus client: cli library guide 2025
prometheus-client Python Guide [2026] | PyPI Tutorial
November 16, 2025 - # Create virtual environment python -m venv myenv # Activate (Linux/Mac) source myenv/bin/activate # Activate (Windows) myenv\Scripts\activate # Install package pip install prometheus-client ... # Import the package import prometheus_client # Basic usage example # Example usage result = prometheus_client() print(result)