可观测性
Keel 的可观测能力分四条独立通道,互不阻塞:健康检查走业务端口,指标与 pprof 走独立监听,追踪经 OTLP 外发。任何一条挂掉都不影响业务请求。
| 通道 | 端点 | 监听 |
|---|---|---|
| 健康检查 | /health/live、/health/ready |
业务端口 8080 |
| 指标 | /metrics |
独立端口,默认 127.0.0.1:19090 |
| pprof | /debug/pprof/* |
独立端口 6060,生产需显式放行 |
| 追踪 | OTLP gRPC | 外发到 collector |
两个端点都在业务端口,无需鉴权、不走 payload 加密、不进认证链:
| 端点 | 语义 | 典型用途 |
|---|---|---|
GET /health/live |
进程能响应即 200 | 容器 liveness、LB 存活判定 |
GET /health/ready |
探测 PostgreSQL 与 Redis | readiness、摘流量 |
就绪探测有 2 秒超时,并按依赖逐个短路:
func readiness(ctx context.Context, db *sql.DB, redisClient *redis.Client) gin.H { ctx, cancel := context.WithTimeout(ctx, 2*time.Second) defer cancel() if db == nil || db.PingContext(ctx) != nil { return gin.H{"status": "unavailable", "postgres": false} } if redisClient.Ping(ctx).Err() != nil { return gin.H{"status": "unavailable", "postgres": true, "redis": false} } return gin.H{"status": "ok", "postgres": true, "redis": true}}响应体直接说明哪个依赖挂了,redis 字段只在 PostgreSQL 通过后才出现:
curl -s http://127.0.0.1:8080/health/ready# {"postgres":true,"redis":true,"status":"ok"}
curl -s -o /dev/null -w "%{http_code}\n" http://127.0.0.1:8080/health/ready# 200(依赖不可用时为 503)不要把 ready 当 liveness 探针。 数据库抖动 30 秒会让 K8s 重启所有 Pod,而重启不会让数据库变快,只会把局部故障放大成全站不可用。镜像的 HEALTHCHECK 用的就是 live。
Prometheus 指标
Section titled “Prometheus 指标”两个延迟直方图
Section titled “两个延迟直方图”| 指标 | 桶 | 观察点 |
|---|---|---|
http_request_duration_seconds |
Prometheus 默认桶 | 请求耗时总量,标签 method / route |
http_server_handler_duration_seconds |
24 个自定义桶,含 le="0.02" |
完整 handler 耗时,标签 method / route / outcome |
自定义桶在 20ms 处有精确边界,因此可以直接算 20ms 达标率:
sum(rate(http_server_handler_duration_seconds_bucket{le="0.02"}[5m]))/sum(rate(http_server_handler_duration_seconds_count[5m]))这条比值就是“多少个请求在 20ms 内完成”,是 Keel 的延迟 SLO。它比 P99 更直观:P99 达标不代表 95% 的请求都舒服。
http_server_handler_duration_seconds 的插桩位置在整个 Gin 引擎之外(metrics.WrapHTTP),所以统计到的是客户端真实感受的耗时,包含 payload 解密与审计入队,而不只是业务 handler。
outcome 标签区分不同结局:
| outcome | 条件 |
|---|---|
success |
正常返回,状态码 2xx/3xx |
rejected |
4xx |
failure |
5xx、panic 或未正常返回 |
canceled |
请求上下文被取消 |
preflight |
OPTIONS 返回 204 |
redirect |
Gin 自动重定向(绕过中间件链) |
failure 与 rejected 分开是关键:客户端 4xx 不该污染“服务端故障”的告警信号。
业务与平台指标
Section titled “业务与平台指标”| 指标 | 类型 | 含义 |
|---|---|---|
http_requests_total |
Counter | 按 method/route/status 的请求数 |
auth_login_failures_total |
Counter | 登录失败次数 |
auth_refresh_replays_total |
Counter | 检测到的 Refresh 重放 |
authz_cache_total |
CounterVec | Casbin 决策缓存命中/未命中 |
authz_enforce_duration_seconds |
Histogram | 缓存未命中时的 Enforce 耗时 |
authz_reloads_total |
CounterVec | 策略热更新结果 |
dependency_up |
GaugeVec | PostgreSQL / Redis 可达性 |
db_pool_* |
Gauge | API PostgreSQL 连接池的使用与等待统计 |
redis_commands_total / redis_batch_duration_seconds |
Counter / Histogram | Redis 命令量与耗时 |
outbox_failed_total |
Counter | 超过重试上限的 outbox 事件 |
job_runs_total |
CounterVec | 定时任务执行结果 |
file_scans_total / storage_failures_total |
Counter | 文件扫描与存储失败 |
audit_queue_depth / audit_queue_dropped_total |
GaugeFunc / Counter | 审计队列积压与丢弃 |
session_revoke_pending |
Gauge | 待清理的会话撤销事件 |
route 标签用路由模板(/api/v1/users/:id)而不是实际路径,否则每个 ID 都会生成一条时间序列,把 Prometheus 打爆;未匹配的路由统一落到 unmatched。
dependency_up 由后台 goroutine 每 15 秒探测一次,与 /health/ready 的区别是:ready 回答“现在能不能接流量”,dependency_up 回答“过去 15 秒依赖是否稳定”,后者能画成时间序列并触发告警。
独立监听,默认 127.0.0.1:6060,路径与标准库一致:
go tool pprof http://127.0.0.1:6060/debug/pprof/profile?seconds=30 # CPUgo tool pprof http://127.0.0.1:6060/debug/pprof/heap # 堆curl -s http://127.0.0.1:6060/debug/pprof/goroutine?debug=1 # goroutine 快照handler 显式注册在独立 mux 上,http.DefaultServeMux 从不被服务:
func newPProfHandler() http.Handler { mux := http.NewServeMux() mux.HandleFunc("/debug/pprof/", pprof.Index) mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline) mux.HandleFunc("/debug/pprof/profile", pprof.Profile) mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol) mux.HandleFunc("/debug/pprof/trace", pprof.Trace) return mux}生产环境的约束由启动期校验兜住:
app.env=production且pprof_enabled=true但没设pprof_allow_in_prod=true→ 启动失败- 监听非回环地址时不配
OPS_AUTH_TOKEN→ 启动失败 - Compose 的
fullprofile 把PPROF_ADDR设为空串,即完全不监听
排障时不要长期开启:临时绑回环、用 SSH 隧道连过去、抓完立刻关掉,或者只在内网且有 token 的条件下开。
OTel 追踪
Section titled “OTel 追踪”OTLP gRPC 导出,相关变量:OTEL_ENABLED、OTEL_EXPORTER_OTLP_ENDPOINT、OTEL_INSECURE、OTEL_SAMPLE_RATE、OTEL_TIMEOUT。
observability: otel_enabled: true otel_endpoint: "otel-collector:4317" otel_insecure: false # 生产应走 TLS otel_sample_rate: 0.1 # 生产 10% 采样,本地 1.0 otel_timeout: 10s采样器是 ParentBased(TraceIDRatioBased(rate)),批处理超时 5 秒,resource 上带 service.name 与 deployment.environment。span 由 TraceMiddleware 产生,命名从 HTTP <method> 改成 METHOD <route>,并带 request.id 属性。
request.id 是关键:它把日志、追踪、审计三者对齐。
id := strings.TrimSpace(c.GetHeader("X-Request-ID"))if id == "" || len(id) > 100 { id = uuid.NewString()}上游传了 X-Request-ID 就沿用(便于跨网关串联),超过 100 字符则重新生成以防注入;响应头回写同一个值。该 ID 同时写进 sys_logs.request_id 与 span 属性。
实测延迟基线
Section titled “实测延迟基线”基准环境:单实例、本地 PostgreSQL + Redis、全路由经 payload v1 加密、零错误。压测为 rate=100/s × 60s × 2 轮,取两轮中最差值(ms)。
| 指标 | P50 | P95 | P99 |
|---|---|---|---|
GET 全站 |
2.19 | 9.77 | 10.65 |
GET /api/v1/users |
— | — | 4.09 |
GET /api/v1/roles |
— | — | 6.39 |
GET /api/v1/dict-types |
— | — | 2.04 |
GET /api/v1/logs?type=operation |
— | — | 11.17 |
登录是唯一超过 20ms 的常规接口:
| 指标 | P50 | P95 | P99 |
|---|---|---|---|
POST /api/v1/auth/login |
65.9 | 68.2 | 69.4 |
登录耗时由 Argon2id 主导。这是安全下限,不是性能缺陷:把参数调低能让登录立刻变快,代价是离线爆破成本下降几个数量级。目标区间是 P99 ≤ 300ms。
插桩自身开销约 0.002ms(BenchmarkHandlerInstrumentation:950–1968 ns/op、400 B/op、3 allocs/op),相对 0.5ms 预算可忽略。
固定顺序,前三步不需要登录服务器:
- 拿
X-Request-ID:响应头就有;前端报错时应带上它 - 查审计:按
request_id取同一次请求的全部行,看latency_ms、status_code、result,写操作还能看到对应operation行 - 看指标:该路由的
le="0.02"达标率与 P99;同时看authz_cache_total的命中率和audit_queue_depth——策略重载会清空决策缓存,审计积压说明写库跟不上 - 看追踪:在 Tempo 里按 span 属性
request.id搜索,得到瀑布图;确认时间花在解密、鉴权、SQL 还是 Redis - 必要时开 pprof:CPU 高就 profile,内存高就 heap,goroutine 数随时间单调增长就抓 goroutine
# 第 2 步的等价 SQLexport PGPASSWORD='<password>'psql -h <host> -U <user> -d keel -c \ "SELECT type, module, action, status_code, latency_ms FROM sys_logs WHERE request_id = '<id>' ORDER BY type;"压测时注意:/api/v1/* 默认要求 X-Payload 密文头,直接 hey 打只会拿到 428。要么压 /health/ready 验证基础链路,要么用实现了握手的客户端——否则你测的只是“拒绝请求有多快”。
- 运维端点的鉴权与暴露策略:部署与运维
- 审计日志如何支撑排障:统一审计日志
- 授权缓存对延迟的影响:权限:Casbin 三级授权