使用 OpenTelemetry 发送指标
您可通过 OpenTelemetry 协议(OTLP)向 CloudWatch 发送自定义指标。您可使用各类 OTel SDK(Java、Python、Go、.NET、Node.js)、OTel 采集器,或是任意兼容 OTLP 协议的客户端。
CloudWatch OTLP 端点
将指标发送到所在区域的 CloudWatch OTLP 端点:
https://monitoring.region.amazonaws.com/v1/metrics
身份验证使用标准 AWS SigV4 签名机制。服务名称为 monitoring。有关端点、身份验证方案及相关限制的更多信息,请参阅 OTLP 端点。
快速入门:发布首个指标
方案一:OTel 采集器(生产环境推荐)
为 OTel 采集器配置 OTLP HTTP 导出器与 SigV4 身份验证:
receivers: otlp: protocols: grpc: endpoint: 0.0.0.0:4317 http: endpoint: 0.0.0.0:4318 processors: batch: send_batch_size: 200 timeout: 10s exporters: otlphttp: tls: insecure: false metrics_endpoint: "https://monitoring.us-east-1.amazonaws.com/v1/metrics" auth: authenticator: sigv4auth extensions: sigv4auth: service: "monitoring" region: "us-east-1" service: extensions: [sigv4auth] pipelines: metrics: receivers: [otlp] processors: [batch] exporters: [otlphttp]
有关详细设置说明,请参阅开始使用。
方案二:OTel SDK(Python 示例)
from opentelemetry import metrics from opentelemetry.sdk.metrics import MeterProvider from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter # Point at the CloudWatch OTLP endpoint exporter = OTLPMetricExporter( endpoint="https://monitoring.us-east-1.amazonaws.com:443/v1/metrics" ) reader = PeriodicExportingMetricReader(exporter, export_interval_millis=60000) provider = MeterProvider(metric_readers=[reader]) metrics.set_meter_provider(provider) # Create and record a metric meter = metrics.get_meter("my-app") counter = meter.create_counter("http_requests_total", description="Total HTTP requests") counter.add(1, {"method": "GET", "path": "/api/users", "status": "200"})
方案三:OTel SDK(Java 示例)
import io.opentelemetry.api.metrics.Meter; import io.opentelemetry.api.metrics.LongCounter; Meter meter = GlobalOpenTelemetry.getMeter("my-app"); LongCounter counter = meter.counterBuilder("http_requests_total") .setDescription("Total HTTP requests") .build(); counter.add(1, Attributes.of( AttributeKey.stringKey("method"), "GET", AttributeKey.stringKey("path"), "/api/users", AttributeKey.stringKey("status"), "200" ));
所需的 IAM 权限
发送指标的身份主体需具备 cloudwatch:PutMetricData 权限。采用 SigV4 身份验证:绑定下方策略:
{ "Effect": "Allow", "Action": [ "cloudwatch:PutMetricData" ], "Resource": "*" }
若采用持有者令牌身份验证,请参阅为指标设置持有者令牌身份验证。
验证指标已接入
打开 CloudWatch 控制台,进入 Query Studio,然后执行查询语句:
http_requests_total
指标通常在首次发送数据点后的 1 – 2 分钟内展示。
支持的指标类型
下表列出 CloudWatch 兼容的 OTel 指标类型,以及对应的 PromQL 查询方式。
| OTel 指标类型 | PromQL 使用方式 |
|---|---|
| 计数器 | 使用 rate() 或 increase() 查询 |
| 计量表 | 直接查询(返回当前值) |
| 直方图 | 使用 histogram_quantile() 计算百分位数 |
最佳实践
通过 OTLP 发送指标时,请采纳以下建议:
-
使用表意清晰的指标名称:遵循 OTel 命名规范(示例:
http.server.request.duration或http_request_duration_seconds)。 -
合理控制标签基数:切勿将请求 ID、UUID 这类高唯一值作为标签值。
-
设置合理的导出间隔:标准推荐 60 秒。采集间隔越短,产生的成本越高。
-
善用资源属性:服务名称、版本、运行环境等静态元数据统一放置在资源属性中,不要放在每个数据点的标签内。