普罗米修斯如何使用start_http_server在多进程应用程序中公开度量



如何在多进程应用程序中使用start_http_server 公开度量

我在互联网上发现了很多gunicorn的例子,但我想使用start_http_server

我应该如何处理下面的代码才能使其正常工作?

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)

我也在想同样的事情,解决方案就像你想象的那样简单。

更新了您的示例代码以工作:


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

最新更新