一个简单的程序
这里使用Python3语言,创建虚拟环境,并安装prometheus_client
mkvirtualenv --python "/usr/local/python36/bin/python3" prom pip install prometheus_client
编写一个简单的HTTP服务器(运行在192.168.88.50上)
import http.server from prometheus_client import start_http_server class MyHandler(http.server.BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.end_headers() self.wfile.write(b"Hello world") if __name__ == "__main__": start_http_server(8000) # 在8000端口上启动一个http服务器给promethes metrics 提供服务 server = http.server.HTTPServer(('localhost', 8001), MyHandler) server.serve_forever()
访问http://192.168.88.50:8000/metrics查看
可以把它配置到prometheus服务中, 编辑prometheus.yml,添加如下配置, 并重启prometheus
- job_name: "demo" static_configs: - targets: - "192.168.88.50:8000"
现在我们可以从prometheus中获取指标数据
Counter
counter是一种会经常使用到指标类型,只增不减(除非发生重置),例如我们可以在应用程序中记录某些事件发生的次数,通过以时序的形式存储这些数据,我们可以轻松的了解该事件产生速率的变化。
扩展前面的代码,增加一个新的mertic: 请求Hello World的次数
from prometheus_client import Counter # 第1个参数是mertic name必须是唯一的, 第二个参数是对mertic的描述 REQUESTS = Counter('hello_worlds_total', 'Hello worlds requested.') class MyHandler(http.server.BaseHTTPRequestHandler): def do_GET(self): REQUESTS.inc() # 递增 self.send_response(200) self.end_headers() self.wfile.write(b"Hello world")
当我们在192.168.88.50上每访问一次(curl http://127.0.0.1:8001), 则 'hello_worlds_total'的值就是增加1
使用PromQL表达式查看 请求的速率
Counting Exceptions
客户端库不仅提供核心功能,还提供了实用的方法。在Python中计算异常我们可以直接利用count_exceptions上下文管理器和装饰器。
import random from prometheus_client import Counter REQUESTS = Counter('hello_worlds_total', 'Hello worlds requested.') EXCEPTIONS = Counter('hello_word_excpetions_total', 'Exceptions serving Hello World.') class MyHandler(http.server.BaseHTTPRequestHandler): def do_GET(self): REQUESTS.inc() # 这里我们使用随机数才产生异常,通过count_exceptions能够记录发生异常的次数,并且不干扰程序逻辑 with EXCEPTIONS.count_exceptions(): if random.random() < 0.2: raise Exception self.send_response(200) self.end_headers() self.wfile.write(b"Hello world")