Go以Google API Client Libraries來取得CloudWatch metric統計資料。
事前要求
參考「AWS EC2 建立instance」建立一個instance,為CloudWatch指標的統計資料對象。
參考「Golang 建立AWS CloudWatch API client」建立CloudWatch API client。
取得metric統計資料
呼叫cloudwatch.Client.GetMetricStatistics
,傳入cloudwatch.GetMetricStatisticsInput
參數來取得metric統計資料。
cloudwatch.GetMetricStatisticsInput
欄位如下:
MetricName
- 填入指標(metric)名稱。StartTime
- 統計起始時間。EndTime
- 統計結束時間。Period
- 統計時間刻度,單位為秒,例如600
即為600秒,也就是每10分鐘統計一次。NamceSpace
- Metrics分類名稱,項下有多種指標。參考namcespace列表。Statistics
- 統計指標,例如平均值(Average)、最大值(Maximum)。Dimensions
- 用來識別指標對象的名值對參數,Name
為維度名稱,Value
為值。參考EC2的metric dimensions。例如這邊要查循的維度為InstanceId
,值為instance的id。
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)
output, err := client.GetMetricStatistics(ctx, &cloudwatch.GetMetricStatisticsInput{
MetricName: aws.String("CPUUtilization"),
StartTime: aws.Time(time.Date(2024, 3, 5, 14, 0, 0, 0, time.UTC)), // 2024-03-05T14:00:00Z
EndTime: aws.Time(time.Date(2024, 3, 5, 15, 0, 0, 0, time.UTC)), // 2024-03-05T15:00:00Z
Period: aws.Int32(600),
Namespace: aws.String("AWS/EC2"),
Statistics: []types.Statistic{types.StatisticAverage},
Dimensions: []types.Dimension{
{
Name: aws.String("InstanceId"),
Value: aws.String("i-015766eb6a31d3413"),
},
},
})
if err != nil {
panic(err)
}
for _, point := range output.Datapoints {
fmt.Println(*point.Timestamp)
fmt.Println(*point.Average)
fmt.Println(point.Unit)
fmt.Println("========================================")
}
}
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:30:00 +0000 UTC
0.25065857909898137
Percent
========================================
2024-03-05 14:20:00 +0000 UTC
0.23285130082378647
Percent
========================================
2024-03-05 14:50:00 +0000 UTC
0.2331328594860565
Percent
========================================
2024-03-05 14:10:00 +0000 UTC
0.23200473950299177
Percent
========================================
2024-03-05 14:00:00 +0000 UTC
0.2306822395253995
Percent
========================================
2024-03-05 14:40:00 +0000 UTC
0.2328424871449593
Percent
========================================
沒有留言:
張貼留言