在微服务与高并发场景下,HTTP 状态码(如 200、404、500)是衡量服务健康的关键指标。通过 Prometheus 抓取状态码数据,结合 Grafana 的可视化能力,可实现实时监控、告警与深度分析。以下是具体实现步骤:
1. 数据采集:暴露 HTTP 状态码指标****
·
Nginx/Apache 指标导出
通过 nginx-module-vts 或 mod_status 插件,将 Nginx/Apache 的状态码统计暴露为 Prometheus 可抓取的端点(如 /metrics)。示例:
·
·
nginx
·
·
| location /metrics { | |
|---|---|
| vts_export on; | |
| access_log off; | |
| } |
·
或使用 textfile 目录手动导出自定义指标(如 Shell 脚本统计日志)。
·
·
应用层指标(如 Spring Boot)
通过 Micrometer 或 Prometheus 客户端库,在代码中暴露状态码计数器:
·
·
java
·
·
| @Bean | |
|---|---|
| public MeterRegistryCustomizer metricsCommonTags() { | |
| return registry -> registry.config().commonTags("application", "my-service"); | |
| } | |
| @GetMapping("/example") | |
| public ResponseEntity example() { | |
| httpStatusCounter.labels("200").inc(); // 自定义计数器 | |
| return ResponseEntity.ok("Success"); | |
| } |
·
2. Prometheus 配置:抓取与存储状态码****
· 配置抓取任务
在 prometheus.yml 中定义目标(如 Nginx 或应用服务):
·
yaml
·
·
| scrape_configs: | |
|---|---|
| - job_name: 'nginx-vts' | |
| static_configs: | |
| - targets: ['nginx-server:8080'] | |
| - job_name: 'my-service' | |
| metrics_path: '/actuator/prometheus' | |
| static_configs: | |
| - targets: ['app-server:8081'] |
·
· 关键指标示例
Prometheus 会抓取类似以下指标:
·
| nginx_http_requests_total{status="200"} 1234 | |
|---|---|
| nginx_http_requests_total{status="500"} 5 | |
| http_server_requests_seconds_count{status="404"} 10 |
·
3. Grafana 可视化:构建状态码仪表盘****
· 核心面板设计
· 状态码分布图:使用 Stat 或 Pie Chart 面板展示 2xx/4xx/5xx 的占比。
· 时间趋势图:通过 Time Series 面板绘制各状态码的请求量变化曲线。
· TOP 错误码:使用 Bar Gauge 面板突出显示高频错误(如 404/500)。
· 动态阈值告警
在 Grafana 中配置告警规则,当 5xx 错误率超过阈值(如 1%)时触发通知(邮件/Slack)。
4. 高级分析场景****
· 错误码根因定位
结合日志(如 Loki)与状态码,快速关联错误请求的上下文信息。
· 服务关联分析
通过 Prometheus 的 record rules 计算跨服务调用链中的状态码关联性(如 A 服务 500 导致 B 服务 404)。
5. 优化与扩展****
· 高基数优化
对状态码(如 URL 路径)添加标签过滤,避免指标爆炸。
· 自动化告警
使用 Prometheus Alertmanager 集成 Grafana 的告警规则,实现多级通知(如首次触发、持续告警)。
通过 Prometheus + Grafana 的组合,HTTP 状态码监控从简单的计数升级为可追溯、可预警的完整体系。无论是排查故障还是优化用户体验,这一方案都能提供关键数据支撑。