Prometheus简单示例
Prometheus简单示例
Prometheus
Prometheus 是一款基于时序数据库的开源监控告警系统。Prometheus的基本原理是通过HTTP协议周期性抓取被监控组件的状态,任意组件只要提供对应的HTTP接口就可以接入监控。不需要任何SDK或者其他的集成过程。
示例
下载安装启动
wget https://github.com/prometheus/prometheus/releases/download/v2.37.6/prometheus-2.37.6.linux-amd64.tar.gz
tar xvfz prometheus-2.37.6.linux-amd64.tar.gz
cd prometheus-2.37.6.linux-amd64/
./prometheus --config.file=prometheus.yml
此时打开http://localhost:9090/即可以看到监控界面
Go客户端编写
package main
import (
"net/http"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
func main() {
//提供 /metrics HTTP 端点
http.Handle("/metrics", promhttp.Handler())
//端口号
http.ListenAndServe(":2112", nil)
}
运行后访问http://localhost:2112/metrics可以看到采集的指标数据
注册自定义应用程序指定指标:
package main
import (
"net/http"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
func recordMetrics() {
//每2秒,计数器增加1。
go func() {
for {
opsProcessed.Inc()
time.Sleep(2 * time.Second)
}
}()
}
// 公开了 myapp_processed_ops_total 计数器
var (
opsProcessed = promauto.NewCounter(prometheus.CounterOpts{
Name: "myapp_processed_ops_total",
Help: "The total number of processed events",
})
)
func main() {
recordMetrics()
http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":2112", nil)
}
运行后访问http://localhost:2112/metrics可以看到自定义的指标,每2秒,计数器增加1
服务端看板
可以修改配置文件:prometheus.yml
# my global config
global:
scrape_interval: 15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
# scrape_timeout is set to the global default (10s).
# Alertmanager configuration
alerting:
alertmanagers:
- static_configs:
- targets:
# - alertmanager:9093
# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
# - "first_rules.yml"
# - "second_rules.yml"
# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
# The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
- job_name: "prometheus"
# metrics_path defaults to '/metrics'
# scheme defaults to 'http'.
static_configs:
- targets: ["localhost:2112"]
将最后的targets修改成客户端启动的端口即可
Prometheus简单示例
https://zhangzhao219.github.io/2023/03/02/Backend/Prometheus/