本节介绍如何在python应用中集成prometheus client,收集web应用的访问量数据。主要流程如下:
安装依赖:
pip3 install prometheus_client
pip3 install web.py
创建python文件:
mkdir example_app & cd example_app
touch variable.py
touch main.py
variable.py
代码:
import prometheus_client
REQUESTS = prometheus_client.Counter('total_requests', "Total requests for all page view")
main.py
:
import prometheus_client
import web
import variable # 引用
urls = (
'/hello', 'Hello',
)
class Hello:
def GET(self):
variable.REQUESTS.inc() # 加1
web.header('Access-Control-Allow-Origin', '*')
web.header('Content-Type', 'text/json; charset=utf-8', unique=True)
web.header('Access-Control-Allow-Credentials', 'true')
return "hello"
if __name__=="__main__":
client = prometheus_client.start_http_server(5001)
app = web.application(urls, globals())
app.run()
运行程序:
python3 main.py # 默认运行在8080端口
不断刷新页面:
访问5001端口,可以查看总请求量数据: