写在前面:
本次实战的主要目标为:通过在程序中集成进prometheus来暴露一些统计指标,部署Prometheus进行采集,部署Grafana配置Prometheus数据源并进行Dashboard展示。
一、C++程序中集成Prometheus暴露指标
参考:可选择相应的开发语言 https://prometheus.io/docs/instrumenting/clientlibs/
备注:本文实战程序为C++;
1、git拉取代码到本地,起一个干净的centos7容器便于进行代码编译测试,可将本地代码目录挂载到容器目录,将宿主机端口8080与容器端口8080做映射,使得在容器内C++程序将指标暴露于8080端口后,可以通过访问地址 http://ip:8080/metrics 看到暴露的指标,同时供Prometheus采集;
2、对于官网提供的prometheus-cpp,要进行编译和测试其中的sample,需要先升级gcc版本,已在centos7容器内gcc 7.3.1下测试成功。编译过程按照/prometheus-cpp/README.md文档中的"via CMake"部分编译即可,编译成功后在/prometheus-cpp/_build/bin/目录下启动sample_server,然后通过访问地址 http://ip:8080/metrics 就可以看到样例程序暴露的指标。
具体参考:Linux 安装指定版本GCC方法_gcc --version_早安试言的博客-CSDN博客
3、在自己的程序中集成进prometheus的逻辑。
通过访问8080端口看到的指标效果应当是:每次刷新页面,指标的值都会发生变化。
// create a http server running on port 8080
prometheus::Exposer exposer{"localhost:8080"};
// create a metrics registryip
auto registry_test = std::make_shared<prometheus::Registry>();
// add new gauge family to the registry
auto& Num = prometheus::BuildGauge()
.Name("Num")
.Help("writeToPrometheus_Num")
.Register(*registry_test);
Num.Add({{"field","Num"}})
.Set(ptr->Num);
//注:暴露多个指标就构建多个BuildGauge,并相应的通过Add设置值
exposer.RegisterCollectable(registry_test);
// Auth
exposer.RegisterAuth([](const std::string& user, const std::string& password){
return user == "admin" && password == "admin";},"Test Exportor");
Prometheus定义了四种不同的指标类型:Counter(计数器)、Gauge(仪表盘)、Histogram(直方图)、Summary(摘要),具体选择哪种指标类型,要根据要暴露的指标特点进行选择。
二、部署安装Prometheus进行采集
wget https://github.com/prometheus/prometheus/releases/download/v2.26.0/prometheus-2.26.0.linux-amd64.tar.gz
tar -zxvf prometheus-2.26.0.linux-amd64.tar.gz
mv prometheus-2.26.0.linux-amd64 prometheus2.26
//配置监控
修改prometheus.yml文件,增加如下内容,即配置采集本机8080端口暴露的指标:
- job_name: 'statistics'
static_configs:
- targets: ['localhost:8080']
//启动
./prometheus --config.file=prometheus.yml &
//访问
http://IP:9090/
在Status下的Targets中即可看到配置的监控对象
参考:https://blog.csdn.net/zhangcongyi420/article/details/122776811
三、部署Grafana并展示采集数据
wget https://dl.grafana.com/oss/release/grafana-7.3.6.linux-amd64.tar.gz
tar -zxvf grafana-7.3.6.linux-amd64.tar.gz
cd ./grafana-7.3.6/bin
//启动
./grafana-service
//访问打开界面
http://ip:3000/
//将prometheus添加为数据源
//创建Dashboard选择合适的图形进行展示,Dashboard可导出
参考:CentOS7安装可移植Prometheus+grafana--基础搭建_centos7安装prometheus_丰耳的博客-CSDN博客