Clement Ros
Clement Ros

Reputation: 329

How to create custom metrics in prometheus?

I'm setting up a monitoring PoC for future requirements. The PoC is developed locally on my computer. To monitor metric i use Prometheus and Grafana. I want to count the number of files received and the time spend to process it. For that i need to create custom metrics.

I'm using python 2.7.5. For now i have linked Prometheus and the target. I receive metrics but don't know how to create metrics that i want.

counter = prom.Counter('python_my_counter', 'This is my counter')
gauge = prom.Gauge('python_my_gauge', 'This is my gauge')
histogram = prom.Histogram('python_my_histogram', 'This is my histogram')
summary = prom.Summary('python_my_summary', 'This is my summary')


def thr():
    while True:
        counter.inc(random.random())
        gauge.set(random.random() * 15 - 5)
        histogram.observe(random.random() * 10)
        summary.observe(random.random() * 10)
        process_request(random.random() * 5)

        time.sleep(1)

I expect the sum of files received "count the number of files received" metric. The time spent processing a file (i.e 2s) and the sum of time spent processing a file (50s).

Upvotes: 5

Views: 23167

Answers (1)

kalimba
kalimba

Reputation: 418

you don't need all these metrics for your use case. Just register summary metric with prometheus, something like:

from prometheus_client import Summary
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)

Then you have request_processing_seconds_count and request_processing_seconds_sum metrics available.

Upvotes: 6

Related Questions