简体   繁体   English

Prometheus 如何使用 start_http_server 在多进程应用程序中公开指标

[英]Prometheus how to expose metrics in multiprocess app with start_http_server

How expose metrics in multiprocess app use start_http_server如何在多进程应用程序中公开指标使用 start_http_server

I found many examples with gunicorn in internet but i want use start_http_server我在互联网上发现了很多 gunicorn 的例子,但我想使用 start_http_server

what should i do with code below to make it work properly?我应该如何处理下面的代码以使其正常工作?

from multiprocessing import Process
import time, os
from prometheus_client import start_http_server, multiprocess, CollectorRegistry, Counter


MY_COUNTER = Counter('my_counter', 'Description of my counter')
os.environ["PROMETHEUS_MULTIPROC_DIR"] = "tmp"

def f():
    print("+1")
    MY_COUNTER.inc()

if __name__ == '__main__':
    start_http_server(8000)
    p = Process(target=f, args=())
    a = p.start()
    p2 = Process(target=f, args=())
    p2.start()
    time.sleep(1)
    print("collect")
    registry = CollectorRegistry()
    data = multiprocess.MultiProcessCollector(registry)
    while True:
        time.sleep(1)

I was figuring out the same thing, and the solution was as simple as you would imagine.我也在想同样的事情,解决方案和你想象的一样简单。

Updated your example code to work:更新了您的示例代码以使其正常工作:


from multiprocessing import Process
import shutil
import time, os
from prometheus_client import start_http_server, multiprocess, CollectorRegistry, Counter


# ensure variable exists, and ensure defined folder is clean on start
prome_stats = os.environ["PROMETHEUS_MULTIPROC_DIR"]
if os.path.exists(prome_stats):
    shutil.rmtree(prome_stats)
os.mkdir(prome_stats)

MY_COUNTER = Counter('my_counter', 'Description of my counter')

def f():
    while True:
        time.sleep(1)
        print("+1")
        MY_COUNTER.inc()

if __name__ == '__main__':

    # pass the registry to server
    registry = CollectorRegistry()
    multiprocess.MultiProcessCollector(registry)
    start_http_server(8000, registry=registry)

    p = Process(target=f, args=())
    a = p.start()
    p2 = Process(target=f, args=())
    p2.start()

    print("collect")

    while True:
        time.sleep(1)

localhost:8000/metrics
# HELP my_counter_total Multiprocess metric
# TYPE my_counter_total counter
my_counter_total 16.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM