Go以Google API Client Libraries來取得CloudWatch metric資料。
事前要求
參考「AWS EC2 建立instance」建立一個instance,為CloudWatch指標的統計資料對象。
參考「Golang 建立AWS CloudWatch API client」建立CloudWatch API client。
取得metric資料
呼叫cloudwatch.Client.GetMetricData
,傳入cloudwatch.GetMetricDataInput
參數來取得metric統計資料。
cloudwatch.GetMetricDataInput
欄位如下:
NextToken
- 前一次請求返回的token,用來取得下一組的資料。StartTime
- 統計起始時間。EndTime
- 統計結束時間。type.MetricDataQuery
-Id
- Query的Id,以此來識別回應中對應的查詢結果。Expression
- 表示Metric insight query和Math expression。Period
- 要取得指標的時間間隔。
types.MetricStat
-Metric
- 要取得的指標。Period
- 要取得指標的時間間隔。Stat
- 統計指標,例如平均值(Average)、最大值(Maximum)。
main.go
package main
import (
"context"
"fmt"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/cloudwatch"
"github.com/aws/aws-sdk-go-v2/service/cloudwatch/types"
)
func main() {
ctx := context.TODO()
client := NewCloudWatchClient(ctx)
var nextToken *string
for {
output, err := client.GetMetricData(ctx, &cloudwatch.GetMetricDataInput{
NextToken: nextToken,
StartTime: aws.Time(time.Date(2024, 3, 5, 14, 0, 0, 0, time.UTC)), // 2024-03-05T14:00:00Z
MetricDataQueries: []types.MetricDataQuery{
{
Id: aws.String("q1"),
Expression: aws.String("AVG(METRICS())"),
Period: aws.Int32(600),
},
{
Id: aws.String("m1"),
MetricStat: &types.MetricStat{
Metric: &types.Metric{
Namespace: aws.String("AWS/EC2"),
MetricName: aws.String("CPUUtilization"),
Dimensions: []types.Dimension{
{
Name: aws.String("InstanceId"),
Value: aws.String("i-015766eb6a31d3413"),
},
},
},
Period: aws.Int32(600),
Stat: aws.String("Average"),
},
},
},
})
if err != nil {
panic(err)
}
for _, r := range output.MetricDataResults {
if *r.Id == "q1" {
for _, t := range r.Timestamps {
fmt.Println(t)
}
for _, v := range r.Values {
fmt.Println(v)
}
}
}
if output.NextToken == nil {
break
}
}
}
func NewCloudWatchClient(ctx context.Context) *cloudwatch.Client {
cfg, err := config.LoadDefaultConfig(
ctx,
config.WithRegion("ap-northeast-1"),
)
if err != nil {
panic(err)
}
return cloudwatch.NewFromConfig(cfg) // Create an Amazon CloudWatch service client
}
測試
執行Go應用程式印出以下。
2024-03-05 14:50:00 +0000 UTC
2024-03-05 14:40:00 +0000 UTC
2024-03-05 14:30:00 +0000 UTC
2024-03-05 14:20:00 +0000 UTC
2024-03-05 14:10:00 +0000 UTC
2024-03-05 14:00:00 +0000 UTC
0.2331328594860565
0.2328424871449593
0.25065857909898137
0.23285130082378647
0.23200473950299177
0.2306822395253995
沒有留言:
張貼留言