Serverless 监控告警:基于 CloudWatch+Prometheus 的指标采集与告警配置
·
Serverless 监控告警:基于 CloudWatch + Prometheus 的指标采集与告警配置
1. 整体架构
- 数据流:
Serverless 服务(如 AWS Lambda)产生指标 → CloudWatch 采集存储 → Prometheus 通过 Exporter 拉取 → Alertmanager 触发告警 - 核心组件:
- CloudWatch:原生监控服务,自动采集 Lambda 的$CPU$、内存、调用次数等指标
- Prometheus:通过
cloudwatch_exporter抓取 CloudWatch 数据,存储为时序数据 - Alertmanager:基于 Prometheus 规则触发告警
2. 指标采集配置
(1) CloudWatch 自动采集
Lambda 默认向 CloudWatch 推送以下指标:
- 调用次数(
Invocations) - 错误率(
Errors) - 持续时间(
Duration) - 并发数(
ConcurrentExecutions)
(2) 部署 CloudWatch Exporter
步骤:
- 创建 IAM 角色,授予 Exporter 读取 CloudWatch 的权限
- 配置 Exporter 的
config.yml,定义需抓取的指标:
region: us-east-1
metrics:
- aws_namespace: AWS/Lambda
aws_metric_name: Duration
aws_dimensions: [FunctionName]
aws_statistics: [Average]
- 启动 Exporter 暴露端口(默认 9106)
(3) Prometheus 抓取配置
在prometheus.yml中添加:
scrape_configs:
- job_name: cloudwatch
static_configs:
- targets: ['exporter-ip:9106']
3. 告警规则配置
(1) Prometheus 告警规则
在alerts.yml中定义阈值规则:
groups:
- name: lambda-alerts
rules:
- alert: HighErrorRate
expr: sum(rate(AWSLambda_Errors_total[5m])) by (FunctionName) > 0.05
for: 10m
labels:
severity: critical
annotations:
summary: "高错误率: {{ $labels.FunctionName }}"
description: "5分钟内错误率超过5%"
公式说明:
错误率计算:$\text{错误率} = \frac{\sum \text{错误调用次数}}{\sum \text{总调用次数}}$
阈值判断:$\text{错误率} > 0.05$
(2) Alertmanager 路由配置
route:
receiver: slack-notifications
receivers:
- name: slack-notifications
slack_configs:
- api_url: 'https://hooks.slack.com/services/...'
channel: '#serverless-alerts'
4. 关键优化实践
- 冷启动监控:
通过自定义指标$(\text{InitDuration} > 1000\text{ms})$捕获 Lambda 冷启动延迟 - 成本关联告警:
设置 $\text{ConcurrentExecutions} \times \text{Duration} > \text{预算阈值}$ - 动态采样:
对高流量函数使用$\text{采样率} = \frac{1}{\log_2(\text{调用次数})}$降低存储开销
5. 验证流程
graph LR
A[Lambda触发] --> B(CloudWatch存储指标)
B --> C{Exporter抓取}
C --> D[Prometheus计算规则]
D --> E>Alertmanager触发]
E --> F[[Slack/邮件告警]]
注:该方案优势在于
- 利用 CloudWatch 免管理采集
- 通过 Prometheus 实现灵活的多维度告警
- 避免在 Serverless 环境中部署完整 Agent 的资源消耗
更多推荐
所有评论(0)