一、方案总览
本方案核心目标:通过 Prometheus 自定义Exporter/代码埋点,采集应用层核心指标(如接口QPS、响应耗时、错误数、业务指标等),将指标存储到Prometheus时序库,再通过Grafana配置可视化面板,实现应用监控的实时展示、异常告警,全程可落地、可扩展,适配Java/Python/Go等主流开发语言。
整体架构流程(闭环):
应用埋点/自定义Exporter → Prometheus拉取指标 → Prometheus存储时序数据 → Grafana对接Prometheus → 可视化大屏展示 → 告警规则配置(可选)
核心优势:自定义灵活,可精准采集业务相关指标(区别于服务器/中间件监控),适配各类自研应用,无需复杂改造,开发成本低、维护简单。
二、技术选型(统一技术栈,降低复杂度)
| 组件 | 选型 | 核心作用 |
|---|---|---|
| 指标采集 | 1. 代码埋点(Prometheus Client SDK);2. 自定义Exporter(Go/Java) | 生成Prometheus可识别的指标(符合Prometheus数据规范) |
| 指标存储 | Prometheus(已部署,沿用之前环境) | 存储时序指标,支持PromQL查询 |
| 可视化展示 | Grafana(已部署,沿用之前环境) | 配置面板,展示应用指标趋势、瞬时值、统计数据 |
| 告警(可选) | Prometheus AlertManager + Grafana告警 | 指标异常时触发告警(钉钉/企业微信) |
| 开发语言 | 示例:Java(SpringBoot)、Go(主流Exporter开发语言) | 适配不同应用技术栈,提供对应埋点方案 |
三、核心前提(必做准备)
1. 已完成 Prometheus + Grafana 部署(参考之前教程),确保Prometheus可正常启动、Grafana可正常访问并对接Prometheus数据源。
2. 应用可正常运行,具备开发权限(可修改代码进行埋点,或部署自定义Exporter)。
3. 网络互通:应用服务器(埋点/Exporter)与Prometheus服务器可互通,确保Prometheus能拉取应用指标(默认端口可自定义,需放行防火墙)。
4. 明确监控指标需求(核心!):提前梳理需要采集的应用指标,避免无意义埋点,推荐分类如下:
- 接口指标:QPS、响应耗时(平均值/最大值/95分位值)、接口错误数、错误率
- 应用运行指标:JVM内存(堆/非堆)、线程数、GC次数/耗时(Java应用);进程CPU/内存占用(通用)
- 业务指标:登录人数、订单量、支付成功率、接口调用量(根据自身业务定义)
- 健康状态指标:应用存活状态、数据库连接数、缓存命中率
四、自定义指标采集方案(两种方式,按需选择)
两种采集方式核心一致:都是生成Prometheus规范的指标(格式:指标名{标签1=值1,标签2=值2} 数值),区别在于实现方式,按需选择即可。
方式一:代码埋点(推荐,精准采集业务指标,无额外组件)
原理:在应用代码中引入Prometheus Client SDK,通过SDK定义指标、更新指标值,同时暴露一个/metrics接口,供Prometheus拉取。
适配场景:自研应用,可修改代码,需要采集精细化业务指标(如订单量、支付成功率)。
示例1:Java SpringBoot 应用埋点(最常用)
步骤1:引入依赖(pom.xml)
<!-- Prometheus Client 核心依赖 -->
<dependency>
<groupId>io.prometheus</groupId>
<artifactId>simpleclient</artifactId>
<version>0.16.0</version>
</dependency>
<!-- SpringBoot 集成 Prometheus 依赖(自动暴露/metrics接口) -->
<dependency>
<groupId>io.prometheus</groupId>
<artifactId>simpleclient_spring_boot</artifactId>
<version>0.16.0</version>
</dependency>
<!-- 采集JVM指标依赖(可选,自动采集JVM相关指标) -->
<dependency>
<groupId>io.prometheus</groupId>
<artifactId>simpleclient_hotspot</artifactId>
<version>0.16.0</version>
</dependency>
步骤2:启动类添加注解(开启Prometheus监控)
import io.prometheus.client.spring.boot.EnablePrometheusEndpoint;
import io.prometheus.client.spring.boot.EnableSpringBootMetricsCollector;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnablePrometheusEndpoint // 开启Prometheus指标端点
@EnableSpringBootMetricsCollector // 开启SpringBoot指标收集
public class MyAppApplication {
public static void main(String[] args) {
SpringApplication.run(MyAppApplication.class, args);
}
}
步骤3:自定义指标(核心,以接口监控、业务指标为例)
新建指标工具类,定义Prometheus支持的4种指标类型(Counter/Gauge/Histogram/Summary),根据需求选择:
import io.prometheus.client.Counter;
import io.prometheus.client.Histogram;
import io.prometheus.client.Summary;
import org.springframework.stereotype.Component;
@Component
public class PrometheusMetricsUtil {
// 1. Counter(计数器,只增不减):接口调用次数、错误数、订单量
// 标签:interface_name(接口名)、method(请求方式)
public static final Counter INTERFACE_CALL_COUNT = Counter.build()
.name("app_interface_call_count") // 指标名(自定义,规范:应用名_指标类型_指标描述)
.help("应用接口调用总次数") // 指标说明
.labelNames("interface_name", "method") // 标签(用于筛选不同接口)
.register(); // 注册指标
// 计数器:接口错误次数
public static final Counter INTERFACE_ERROR_COUNT = Counter.build()
.name("app_interface_error_count")
.help("应用接口调用错误次数")
.labelNames("interface_name", "method", "error_type") // 增加错误类型标签
.register();
// 2. Histogram(直方图):接口响应耗时分布(统计不同区间的耗时次数)
public static final Histogram INTERFACE_RESPONSE_TIME_HISTOGRAM = Histogram.build()
.name("app_interface_response_time_histogram")
.help("应用接口响应耗时分布(单位:秒)")
.labelNames("interface_name", "method")
.buckets(0.1, 0.2, 0.5, 1.0, 2.0, 5.0) // 耗时区间(0.1s内、0.1-0.2s等)
.register();
// 3. Summary(摘要):接口响应耗时百分比(如95分位、99分位耗时)
public static final Summary INTERFACE_RESPONSE_TIME_SUMMARY = Summary.build()
.name("app_interface_response_time_summary")
.help("应用接口响应耗时百分比(单位:秒)")
.labelNames("interface_name", "method")
.quantile(0.95, 0.01) // 95分位耗时,误差允许1%
.quantile(0.99, 0.01) // 99分位耗时
.register();
// 4. Gauge(仪表盘,可增可减):在线人数、数据库连接数
public static final Gauge ONLINE_USER_COUNT = Gauge.build()
.name("app_online_user_count")
.help("应用在线用户数")
.register();
// 业务指标:订单量(Counter)
public static final Counter ORDER_COUNT = Counter.build()
.name("app_order_count")
.help("应用订单总数量")
.labelNames("order_type", "pay_status") // 标签:订单类型、支付状态
.register();
}
步骤4:在接口中埋点(更新指标值)
以SpringBoot接口为例,在接口调用前、调用后、异常时更新对应指标:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.TimeUnit;
@RestController
public class TestInterfaceController {
// 示例1:GET接口埋点
@GetMapping("/api/test")
public String testInterface() {
// 1. 记录接口调用次数(Counter自增)
PrometheusMetricsUtil.INTERFACE_CALL_COUNT.labels("/api/test", "GET").inc();
// 2. 记录接口响应耗时(Histogram/Summary)
Histogram.Timer timer = PrometheusMetricsUtil.INTERFACE_RESPONSE_TIME_HISTOGRAM.labels("/api/test", "GET").startTimer();
Summary.Timer summaryTimer = PrometheusMetricsUtil.INTERFACE_RESPONSE_TIME_SUMMARY.labels("/api/test", "GET").startTimer();
try {
// 模拟接口业务逻辑(耗时0.1-0.5秒)
TimeUnit.MILLISECONDS.sleep((long) (Math.random() * 400 + 100));
return "success";
} catch (Exception e) {
// 3. 记录接口错误次数
PrometheusMetricsUtil.INTERFACE_ERROR_COUNT.labels("/api/test", "GET", e.getClass().getSimpleName()).inc();
throw new RuntimeException(e);
} finally {
// 停止计时,更新耗时指标
timer.observeDuration();
summaryTimer.observeDuration();
}
}
// 示例2:业务指标埋点(订单提交接口)
@PostMapping("/api/order/submit")
public String submitOrder(String orderType, String payStatus) {
// 订单量自增
PrometheusMetricsUtil.ORDER_COUNT.labels(orderType, payStatus).inc();
// 模拟在线用户数(随机更新,实际应从缓存/数据库获取)
PrometheusMetricsUtil.ONLINE_USER_COUNT.set((long) (Math.random() * 1000 + 500));
return "order_submit_success";
}
}
步骤5:验证指标是否正常暴露
启动SpringBoot应用,访问接口:http://应用IP:应用端口/metrics
若能看到自定义的指标(如app_interface_call_count、app_order_count),说明埋点成功,示例如下:
# HELP app_interface_call_count 应用接口调用总次数
# TYPE app_interface_call_count counter
app_interface_call_count{interface_name="/api/test",method="GET"} 10.0
# HELP app_interface_response_time_histogram 应用接口响应耗时分布(单位:秒)
# TYPE app_interface_response_time_histogram histogram
app_interface_response_time_histogram_bucket{interface_name="/api/test",method="GET",le="0.1"} 2.0
app_interface_response_time_histogram_bucket{interface_name="/api/test",method="GET",le="0.2"} 5.0
# HELP app_online_user_count 应用在线用户数
# TYPE app_online_user_count gauge
app_online_user_count 867.0
示例2:Go 应用埋点(简洁高效,适合Go开发的应用)
package main
import (
"net/http"
e"
"github.com/prometheus/client_golang/prometheus"
b.com/prometheus/client_golang/prometheus/promhttp"
)
// 1. 定义自定义指标
var (
接口调用次数(Counter)
faceCallCount = prometheus.NewCounterVec(
etheus.CounterOpts{
me: "app_interface_call_count",
H用接口调用总次数",
},
]string{"interface_name", "method"},
)
口响应耗时(Histogram)
ceResponseTime = prometheus.NewHistogramVec(
eus.HistogramOpts{
ame: "app_interface_response_time",
lp: "应用接口响应耗时(单位:秒)",
ckets: []float64{0.1, 0.2, 0.5, 1.0},
]string{"interface_name", "method"},
func init() {
// 2. 注册指标到Prometheus默认注册表
eus.MustRegister(interfaceCallCount)
prometheus.MustRegister(interfaceResponseTime)
}
// 3. 接口处理函数(埋点)
func testHandler(w http.ResponseWriter, r *http.Request) {
调用次数
rfaceCallCount.WithLabelValues("/api/test", "GET").Inc()
/ 记录响应耗时
start := time.Now()
efer func() {
ation := time.Since(start).Seconds()
terfaceResponseTime.WithLabelValues("/api/test", "GET").Observe(duration)
// 模拟业务逻辑
Sleep(100 * time.Millisecond)
w.Write([]byte("success"))
}
func main() {
. 暴露/metrics接口,供Prometheus拉取
htle("/metrics", promhttp.Handler())
. 注册接口
p.HandleFunc("/api/test", testHandler)
启动服务(端口8080)
http.ListenAndServe(":8080", nil)
} // htt // 5tp.Hand // 4 time. }()
in dur d / inte // 记录 prometh )
) [ },
Bu He N prometh interfa // 接 [ elp: "应 Na prom inter // "githu "tim
启动Go应用,访问 http://应用IP:8080/metrics ,即可看到自定义指标。
方式二:自定义Exporter(适合无法修改应用代码的场景)
原理:开发一个独立的Exporter程序,通过接口调用、日志解析、数据库查询等方式,获取应用指标,转换成Prometheus规范格式,暴露/metrics接口供Prometheus拉取。
适配场景:第三方应用、无法修改源码的应用,或指标采集逻辑复杂(如从日志中提取指标)。
核心开发步骤(以Go开发Exporter为例,最简洁)
步骤1:创建Exporter项目,引入依赖
# 初始化项目
go mod init custom-exporter
# 引入Prometheus Client依赖
go get github.com/prometheus/client_golang/prometheus
go get github.com/prometheus/client_golang/prometheus/promhttp
步骤2:开发Exporter核心逻辑(以采集应用接口状态为例)
package main
import (
"net/http"
"time"
"github.com/prometheus/client_golang/prometheus"
b.com/prometheus/client_golang/prometheus/promhttp"
)
// 1. 定义Exporter结构体(存储指标)
type CustomExporter struct {
存活状态(Gauge:1=存活,0=宕机)
interfaceStatus *prometheus.GaugeVec
// 接口响应耗时(Gauge)
nterfaceLatency *prometheus.GaugeVec
}
// 2. 初始化Exporter
func NewCustomExporter() *CustomExporter {
n &CustomExporter{
eStatus: prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "app_interface_status",
lp: "应用接口存活状态(1=正常,0=异常)",
[]string{"interface_name", "url"},
,
aceLatency: prometheus.NewGaugeVec(
etheus.GaugeOpts{
"app_interface_latency",
elp: "应用接口响应耗时(单位:毫秒)",
string{"interface_name", "url"},
),
}
}
// 3. 实现Prometheus的Collector接口(核心:采集指标)
func (e *CustomExporter) Describe(ch chan<- *prometheus.Desc) {
e.interfaceStatus.Describe(ch)
rfaceLatency.Describe(ch)
}
// 4. 采集指标逻辑(定期调用应用接口,获取状态和耗时)
func (e *CustomExporter) Collect(ch chan<- prometheus.Metric) {
// 定义需要采集的应用接口列表
terfaces := []struct {
ame string
string
{
est接口", "http://应用IP:8080/api/test"},
{"订单接口", "http://应用IP:8080/api/order/submit"},
循环采集每个接口的状态和耗时
for _, iface := range interfaces {
t := time.Now()
用接口,判断状态
sp, err := http.Get(iface.url)
ration := time.Since(start).Milliseconds()
err != nil || resp.StatusCode != 200 {
// 接口异常:状态设为0,耗时设为-1
interfaceStatus.WithLabelValues(iface.name, iface.url).Set(0)
e.interfaceLatency.WithLabelValues(iface.name, iface.url).Set(-1)
else {
// 接口正常:状态设为1,记录耗时
e.interfaceStatus.WithLabelValues(iface.name, iface.url).Set(1)
.interfaceLatency.WithLabelValues(iface.name, iface.url).Set(float64(duration))
}
resp.Body.Close()
}
/ 将采集到的指标发送到Prometheus
interfaceStatus.Collect(ch)
interfaceLatency.Collect(ch)
}
func main() {
初始化Exporter
rter := NewCustomExporter()
注册Exporter到Prometheus
etheus.MustRegister(exporter)
// 暴露/metrics接口(端口9101,避免与node-exporter冲突)
andle("/metrics", promhttp.Handler())
/ 启动Exporter服务
tp.ListenAndServe(":9101", nil)
} ht / http.H prom // expo // e. e. / e } e. if du re // 调 star // } {"t } url n in e.inte [] }, H Name: prom interf ) },
He interfac retur i // 应用接口 "githu
步骤3:编译运行Exporter
# 编译(跨平台编译,如Linux AMD64)
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o custom-exporter main.go
# 运行Exporter(后台运行)
nohup ./custom-exporter &
# 验证:访问 http://Exporter服务器IP:9101/metrics
curl http://127.0.0.1:9101/metrics
若能看到 app_interface_status、app_interface_latency 指标,说明Exporter开发成功。
五、Prometheus配置(拉取自定义应用指标)
无论采用哪种采集方式,最终都需要配置Prometheus,让其定期拉取应用暴露的/metrics接口指标。
步骤1:修改Prometheus配置文件
编辑 Prometheus 配置文件 /usr/local/prometheus/conf/prometheus.yml ,在 scrape_configs 中添加应用监控任务:
global:
scrape_interval: 15s # 拉取间隔(默认15秒,可根据需求调整)
evaluation_interval: 15s
rule_files:
- "/usr/local/prometheus/rules/*.yml"
alerting:
alertmanagers:
- static_configs:
- targets:
- 127.0.0.1:9093
scrape_configs:
# 1. 监控Prometheus自身(原有)
- job_name: 'prometheus'
static_configs:
- targets: ['127.0.0.1:9090']
# 2. 监控服务器(原有,node-exporter)
- job_name: 'linux-node'
static_configs:
- targets: ['127.0.0.1:9100']
# 3. 新增:监控自定义应用(代码埋点方式)
- job_name: 'custom-app' # 任务名(自定义)
static_configs:
- targets: ['应用IP:应用端口'] # 应用暴露/metrics的地址(如Java应用:192.168.1.100:8080)
scrape_interval: 10s # 应用指标拉取间隔(可缩短,如10秒,更实时)
metrics_path: '/metrics' # 指标接口路径(默认就是/metrics,可省略)
# 4. 新增:监控自定义Exporter(Exporter方式)
- job_name: 'custom-exporter' # 任务名(自定义)
static_configs:
- targets: ['Exporter服务器IP:9101'] # Exporter暴露/metrics的地址
scrape_interval: 10s
步骤2:重启Prometheus,验证拉取状态
# 重启Prometheus
systemctl restart prometheus
# 查看Prometheus状态
systemctl status prometheus
访问Prometheus Web界面:http://Prometheus服务器IP:9090 → 点击左侧 Status → Targets → 查看 custom-app 和 custom-exporter 任务的状态,若为 UP,说明拉取成功;若为 DOWN,检查网络、应用/Exporter是否正常运行、端口是否放行。
六、Grafana配置(可视化展示自定义应用指标)
前提:Grafana已对接Prometheus数据源(参考之前部署教程,若未对接,先完成数据源配置)。
核心:创建自定义仪表盘(Dashboard),添加面板(Panel),通过PromQL查询自定义指标,实现可视化展示。
步骤1:创建新的仪表盘(Dashboard)
- 登录Grafana(http://Grafana服务器IP:3000,账号密码已修改)。
- 左侧菜单点击「+」→「Dashboard」→「Add a new panel」,进入面板编辑页面。
步骤2:添加面板(Panel),配置PromQL查询(核心)
根据自定义指标类型,编写对应的PromQL查询语句,选择合适的面板类型,以下是常用场景示例(对应前面的埋点指标):
示例1:接口QPS(每秒调用次数)
- 面板类型:Graph(折线图)或 Stat(数值,显示实时QPS)。
- PromQL查询语句(Counter指标,用rate计算每秒增长率):
rate(app_interface_call_count[5m]) - 筛选单个接口:
rate(app_interface_call_count{interface_name="/api/test"}[5m]) - 配置说明:[5m] 表示取最近5分钟的指标数据,计算每秒调用次数,适合看趋势。
示例2:接口响应耗时(平均值/95分位值)
- 面板类型:Graph(折线图)、Gauge(仪表盘,显示瞬时值)。
- 1. 平均响应耗时(Histogram指标):
avg(rate(app_interface_response_time_histogram_sum[5m]) / rate(app_interface_response_time_histogram_count[5m])) - 2. 95分位响应耗时(Summary指标):
app_interface_response_time_summary{quantile="0.95"}
示例3:接口错误率(错误次数/总调用次数)
- 面板类型:Graph(折线图)、Gauge(仪表盘,显示百分比)。
- PromQL查询语句:
rate(app_interface_error_count[5m]) / rate(app_interface_call_count[5m]) * 100 - 说明:计算最近5分钟的错误率,乘以100转换成百分比,可设置阈值(如5%),超过则显示异常。
示例4:业务指标(订单量、在线用户数)
- 1. 在线用户数(Gauge指标):
app_online_user_count面板类型:Gauge(仪表盘)或 Stat(数值)。 - 2. 订单总量(Counter指标,累计值):
app_order_count面板类型:Graph(折线图,看增长趋势)或 Stat(数值,显示累计订单量)。 - 3. 不同类型订单量对比:
sum(app_order_count) by (order_type)面板类型:Bar(柱状图)。
示例5:应用接口存活状态
- 面板类型:Text(文本)或 Gauge(仪表盘,1=正常,0=异常)。
- PromQL查询语句:
app_interface_status{interface_name="test接口"} - 配置说明:可设置阈值,当值为0时,面板显示红色(异常);值为1时,显示绿色(正常)。
步骤3:布局仪表盘,保存配置
- 每个面板配置完成后,点击「Apply」保存面板。
- 拖拽面板调整布局(如顶部放核心指标:QPS、错误率、在线用户数;中间放趋势图:响应耗时、订单量;底部放接口存活状态)。
- 点击仪表盘顶部「Save Dashboard」,输入仪表盘名称(如「自定义应用监控大屏」),选择保存位置,点击「Save」。
步骤4:优化仪表盘(可选,提升体验)
- 设置自动刷新:仪表盘顶部点击「Refresh」,选择刷新频率(如10秒,与Prometheus拉取间隔一致)。
- 添加模板变量:若有多个应用实例/多个接口,可添加模板变量(如interface_name),实现动态筛选。
- 点击仪表盘顶部「Settings」→「Variables」→「Add variable」。
- Name填写「interface_name」,Type选择「Query」,Data source选择「Prometheus」。
- Query填写:label_values(app_interface_call_count, interface_name),点击「Update」。
- 保存变量后,面板的PromQL查询可使用 $interface_name 替换具体接口名,实现动态筛选。
- 设置面板颜色:在面板编辑页面,点击「Visualization」→「Color scheme」,根据指标范围设置颜色(如错误率>5%显示红色,<1%显示绿色)。
七、可选:配置告警规则(指标异常提醒)
当应用指标异常时(如接口错误率过高、响应耗时过长、接口宕机),通过AlertManager/Grafana发送告警通知(钉钉/企业微信)。
方式1:Prometheus + AlertManager 告警(推荐,全局统一告警)
步骤1:创建告警规则文件
# 创建告警规则目录(若不存在)
mkdir -p /usr/local/prometheus/rules
# 新建应用告警规则文件
vi /usr/local/prometheus/rules/app_alert_rules.yml
写入以下告警规则(根据自定义指标调整):
groups:
- name: 应用监控告警规则
rules:
# 1. 接口错误率过高告警(错误率>5%,持续1分钟)
- alert: 接口错误率异常
expr: rate(app_interface_error_count[5m]) / rate(app_interface_call_count[5m]) * 100 > 5
for: 1m
labels:
severity: warning # 告警级别(warning/critical)
annotations:
summary: "接口错误率过高"
description: "接口 {{ $labels.interface_name }} 错误率为 {{ $value | humanizePercentage }},超过5%阈值,持续1分钟,请排查。"
# 2. 接口响应耗时过长告警(95分位耗时>2秒,持续1分钟)
- alert: 接口响应耗时异常
expr: app_interface_response_time_summary{quantile="0.95"} > 2
for: 1m
labels:
severity: warning
annotations:
summary: "接口响应耗时过长"
description: "接口 {{ $labels.interface_name }} 95分位响应耗时为 {{ $value | humanizeDuration }},超过2秒阈值,持续1分钟,请排查。"
# 3. 接口宕机告警(状态为0,持续30秒)
- alert: 接口宕机
expr: app_interface_status == 0
for: 30s
labels:
severity: critical # 紧急告警
annotations:
summary: "接口宕机"
description: "接口 {{ $labels.interface_name }} 已宕机(状态为0),持续30秒,请立即排查。"
# 4. 在线用户数异常(超过2000,持续5分钟)
- alert: 在线用户数异常
expr: app_online_user_count > 2000
for: 5m
labels:
severity: warning
annotations:
summary: "在线用户数异常"
description: "当前在线用户数为 {{ $value }},超过2000阈值,持续5分钟,请关注系统负载。"
步骤2:重启Prometheus,使告警规则生效
systemctl restart prometheus
访问Prometheus Web界面:http://IP:9090 → Alerts,可查看所有告警规则,以及当前告警状态(Inactive/Active/Pending)。
步骤3:配置AlertManager推送告警(钉钉/企业微信)
编辑AlertManager配置文件 /usr/local/prometheus/conf/alertmanager.yml ,添加钉钉/企业微信Webhook地址(获取方式:钉钉/企业微信创建机器人,复制Webhook地址):
global:
resolve_timeout: 5m # 告警恢复后,5分钟内不再推送
route:
group_by: ['alertname'] # 按告警名称分组
group_wait: 10s # 同组告警等待10秒,一起推送
group_interval: 10s # 同组告警间隔10秒推送
repeat_interval: 1h # 同一告警每1小时重复推送一次
receiver: 'dingtalk' # 默认告警接收者
receivers:
- name: 'dingtalk' # 钉钉告警
webhook_configs:
- url: '你的钉钉机器人Webhook地址' # 替换成自己的钉钉Webhook
send_resolved: true # 告警恢复后,推送恢复通知
# 企业微信告警(可选,替换钉钉)
# - name: 'wechat'
# webhook_configs:
# - url: '你的企业微信机器人Webhook地址'
# send_resolved: true
重启AlertManager:
systemctl restart alertmanager
方式2:Grafana自带告警(简单,适合单仪表盘告警)
- 进入需要配置告警的面板,点击「Edit」→「Alert」→「Create Alert」。
- 设置告警条件(如:错误率>5%,持续1分钟),选择告警级别。
- 配置通知渠道:点击「Notification channels」→「Add channel」,选择钉钉/企业微信,填写Webhook地址,保存。
- 保存告警规则,当指标异常时,Grafana会直接推送告警到指定渠道。
八、常见问题排查(避坑指南)
- Prometheus Targets 显示 DOWN:
- 检查应用/Exporter是否正常运行(systemctl status 应用/Exporter)。
- 检查网络:Prometheus服务器能否ping通应用/Exporter服务器,端口是否放行(firewall-cmd –list-ports)。
- 检查应用/Exporter的/metrics接口是否能正常访问(curl http://IP:端口/metrics)。
- Grafana查询不到指标:
- 检查Prometheus数据源是否配置正确(Configuration → Data sources → 测试连接)。
- 检查PromQL查询语句是否正确(可在Prometheus Web界面的Graph中测试查询,看是否有数据)。
- 检查指标是否被Prometheus正确拉取(Prometheus → Graph → 输入指标名,看是否有数据)。
- 指标数据不更新:
- 检查Prometheus scrape_interval 拉取间隔是否设置合理(如10秒)。
- 检查应用埋点代码是否正确(指标是否正确inc()/set())。
- 检查Exporter采集逻辑是否正常(查看Exporter日志,是否有报错)。
- 告警不推送:
- 检查AlertManager是否正常运行(systemctl status alertmanager)。
- 检查Webhook地址是否正确(钉钉/企业微信机器人是否开启,是否有IP白名单限制)。
- 检查告警规则是否触发(Prometheus → Alerts,看告警状态是否为Active)。
九、方案总结与扩展
总结
本方案实现了「自定义指标采集→Prometheus存储→Grafana可视化→告警推送」的完整闭环,两种采集方式适配不同场景,步骤清晰、可落地,新手可直接按照教程操作,无需复杂的运维经验。
核心亮点:自定义灵活,可精准采集业务指标,摆脱“只能监控服务器/中间件”的局限,真正实现应用层、业务层的全面监控。
扩展方向
- 多应用监控:在Prometheus中添加多个job,采集不同应用的指标,在Grafana中创建多个仪表盘,或在一个仪表盘通过模板变量切换。
- 指标持久化:默认Prometheus数据存储在本地,生产环境可配置远程存储(如Thanos、MinIO),实现数据长期保存和集群高可用。
- 日志与指标联动:集成Loki(日志收集),在Grafana中同时展示指标和日志,快速定位接口异常原因。
- 自定义面板模板:将配置好的仪表盘导出为JSON模板,供其他环境导入使用,提高部署效率。