跳到主要内容

Prometheus 常用告警

嵌入的指标

缓存占位符命中计数器

定义指标

var (
// CachePlaceholderHitsCounter 缓存占位符命中计数器
CachePlaceholderHitsCounter = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "cache_placeholder_hits_counter",
},
[]string{"resource_key"})
)

func init() {
prometheus.MustRegister(CachePlaceholderHitsCounter)
}

嵌入代码

	var cacheableObject Cacheable
if err := domain.RecoverToError(func() {
// 从缓存中获取数据
cacheableObject = cd.cc.Restore(key)
}); err != nil { // 如果未命中
// ... 省略

// 统计穿透查询,预防恶意请求
common.CachePlaceholderHitsCounter.With(prometheus.Labels{"resource_key": key}).Inc()
}

配置告警

# 规则: 该指标的增长率 一分钟内>0.1 or 五分钟内>0.5
rate(cache_placeholder_hits_counter[1m]) > 0.1 or rate(cache_placeholder_hits_counter[5m]) > 0.5

统计事件消费时间

var EventConsumeHistogram = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "metadata_event_consume_h_total", // 指标名称
Buckets: []float64{0.2, 0.5, 1, 2, 5, 10, 30}, // 配置几个对应时间计数桶
},
[]string{"method"}, // 设置一个字段名
)

然后我们在消费者的处理逻辑上下文使用这个实例:

func GetMethodName() string {
pc, _, _, _ := runtime.Caller(1)
return runtime.FuncForPC(pc).Name()
}

func ConsumeMessage(message *event.Message) error {
start := time.Now() // 记录开始时间

// 这里是一些耗时的消费逻辑....

vars.EventConsumeHistogram.WithLabelValues(
GetMethodName()).Observe(time.Since(start).Seconds())
return nil
}

// GetMethodName 获取当前方法名
func GetMethodName() string {
pc, _, _, _ := runtime.Caller(1)
return runtime.FuncForPC(pc).Name()
}

常用的告警规则

一分钟内限流频率到达 10%

sum(rate(flow_control_total{pod=~"trade-zxkp-.*",state="blocked"}[1m]))>10

Pod 发生重启

increase_prometheus(kube_pod_container_status_restarts_total{pod=~"mini-service-.*"} [5m]) >= 1

Redis 调用时间(P99)持续大于 1 秒

histogram_quantile(0.99, sum(rate(redis_tracing_h_total_bucket{}[5m])) by (app, kubernetes_pod_name, command_name, le)) > 1

HTTP 调用时间(P99)持续大于 10 秒

histogram_quantile(0.99, sum(rate(http_tracing_h_total_bucket{}[5m])) by (app, kubernetes_pod_name, le)) > 9

SQL 执行时间(P99)持续大于 10 秒

histogram_quantile(0.99, sum(rate(sql_tracing_h_total_bucket{}[5m])) by (app, kubernetes_pod_name, le)) > 10

持续的异常恐慌

rate(recovery_total{}[5m]) > 0.005

轻微的异常恐慌

rate(recovery_total{}[5m]) > 0.001