在 Beego 中暴露异常评分指标供告警
解读
国内生产环境普遍使用 Prometheus + Grafana + Alertmanager 做云原生监控闭环。
面试官真正想确认的是:
- 你能否把“异常”量化成可聚合的指标(错误率、延迟、业务自定义评分);
- 指标如何以 Prometheus 格式暴露;
- 指标命名、标签、采样频率是否符合企业规范;
- 是否能在 Beego 框架内无侵入地埋点,并支持热更新与单实例多租户。
回答时务必给出可直接落地的代码片段与部署要点,避免只讲概念。
知识点
- Beego 的 FilterChain 与 web.Context,可在返回 Response 之后统计状态码、耗时。
- prometheus/client_golang 的四种指标:Counter、Gauge、Histogram、Summary;错误评分通常用 Counter + Histogram 组合。
- 指标命名规范:namespace_subsystem_metric_unit,例如 beego_http_exception_score_total。
- 标签设计:必须包含 {method, uri, status, service},便于切分 P99、错误率。
- 异常评分算法(举例):
score = 0
if status ≥ 500: score += 10
if latency > 1s: score += 5
if bizCode == "ORDER_TIMEOUT": score += 20
把 score 写进 Counter,即可用 rate() 观察每秒异常分。 - 暴露接口:prometheus.Handler() 挂在 /metrics,注册到 Beego 的 web.Get。
- 性能:使用 promauto 包,指标对象全局复用;采样逻辑放 goroutine 池,避免阻塞主链路。
- 告警:Prometheus rule 里配置
expr: rate(beego_http_exception_score_total[2m]) > 30
for: 1m
labels:
severity: critical
team: sre
annotations:
summary: "异常评分突增,当前值 {{ $value }}"
答案
- 创建指标文件 metrics/metrics.go
package metrics
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
)
var (
// 异常评分总量,每出现一次异常就累加对应分值
ExceptionScore = promauto.NewCounterVec(
prometheus.CounterOpts{
Namespace: "beego",
Subsystem: "http",
Name: "exception_score_total",
Help: "Total exception score for alerting",
},
[]string{"method", "uri", "status", "service"},
)
)
- 在 main.go 注册 /metrics 路由
import (
"github.com/beego/beego/v2/server/web"
"github.com/prometheus/client_golang/prometheus/promhttp"
_ "yourProject/metrics" // 触发指标初始化
)
func main() {
web.Get("/metrics", func(ctx *context.Context) {
promhttp.Handler().ServeHTTP(ctx.ResponseWriter, ctx.Request)
})
web.Run()
}
- 编写异常评分过滤器 filters/score.go
package filters
import (
"strconv"
"time"
"yourProject/metrics"
"github.com/beego/beego/v2/server/web/context"
)
func ExceptionScoreFilter(ctx *context.Context) {
start := time.Now()
// 继续处理请求
ctx.Next()
latency := time.Since(start).Seconds()
status := ctx.Output.Status
score := 0
if status >= 500 {
score += 10
}
if latency > 1.0 {
score += 5
}
// 业务层可在 ctx.Input.Data() 里塞自定义错误码,这里简单示例
if ctx.Input.Data()["bizError"] == "ORDER_TIMEOUT" {
score += 20
}
if score > 0 {
metrics.ExceptionScore.WithLabelValues(
ctx.Request.Method,
ctx.Request.URL.Path,
strconv.Itoa(status),
"order-service", // 服务名可配置
).Add(float64(score))
}
}
- 注册过滤器
web.InsertFilter("/*", web.FinishRouter, filters.ExceptionScoreFilter)
- Prometheus 抓取与告警
在 prometheus.yml 添加 job:
- job_name: 'beego-order'
metrics_path: '/metrics'
static_configs:
- targets: ['order-svc:8080']
规则文件 alert-exception.yaml:
groups:
- name: beego-exception
rules:
- alert: BeegoExceptionScoreHigh
expr: rate(beego_http_exception_score_total[2m]) > 30
for: 1m
labels:
severity: critical
annotations:
summary: "Beego 异常评分过高,2 分钟增速 {{ $value }}"
部署后,Grafana 可绘制
rate(beego_http_exception_score_total[5m]) by (uri)
的折线图,Alertmanager 通过钉钉、飞书或企业微信 webhook 通知值班。
拓展思考
- 多租户场景:把租户 ID 作为标签,防止高基数;可用分桶或哈希限制 uri 维度。
- 采样率:高并发接口可降采样,prometheus.Counter 的 Add() 里乘系数 0.1,告警阈值同步下调。
- 链路追踪联动:在 filter 里把 trace-id 写日志,告警消息附带 trace 链接,方便定位。
- 动态阈值:用 Prometheus 的 avg_over_time 做基线,异常分超过基线 3σ 再告警,减少误报。
- 安全:/metrics 接口加内网 IP 白名单,或走 sidecar 暴露给运维网,防止敏感标签外泄。