Go以Google Cloud Client Libraries for Go來取得GCP Cloud Monitoring的metric time series data。
事前要求
參考「Golang 建立GCP執行個體」建立instance,為Monitoring metric要監控的對象。
參考「Golang 建立GCP Monitoring Metric Client」建立monitoring.MetricClient
。
取得Metric time series data
呼叫monitoring.MetricClient.ListTimeSeries
,輸入參數monitoringpb.ListTimeSeriesRequest
取得monitoring.TimeSeriesIterator
迭代器物件。然後在for迴圈中調用monitoring.TimeSeriesIterator.Next
逐筆讀取資料。
參數monitoringpb.ListTimeSeriesRequest
欄位:
Name
- 填入projects/[PROJECT_ID]
,[PROJECT_ID]
為GCP的project id。Filter
- 設定取得哪些資料的篩選器,必須指明指標(metric type)和其他label。參考這裡Interval
- 設定回傳資料的時間間隔。例如下面取得當下時間前10分鐘的資料。
main.go
package main
import (
"context"
"fmt"
"time"
monitoring "cloud.google.com/go/monitoring/apiv3/v2"
"cloud.google.com/go/monitoring/apiv3/v2/monitoringpb"
"github.com/golang/protobuf/ptypes/timestamp"
"google.golang.org/api/iterator"
)
func main() {
ctx := context.Background()
c, err := monitoring.NewMetricClient(ctx)
if err != nil {
panic(err)
}
defer c.Close()
projectId := "project-id-1"
now := time.Now().UTC()
startTime := now.Add(time.Minute * -10).Unix()
endTime := now.Unix()
req := &monitoringpb.ListTimeSeriesRequest{
Name: "projects/" + projectId,
Filter: `
resource.type="gce_instance"
metric.type="compute.googleapis.com/instance/cpu/utilization" AND
metric.labels.instance_name = "instance-1"
`,
Interval: &monitoringpb.TimeInterval{
StartTime: ×tamp.Timestamp{Seconds: startTime},
EndTime: ×tamp.Timestamp{Seconds: endTime},
},
}
it := c.ListTimeSeries(ctx, req)
for {
resp, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
panic(err)
}
for _, p := range resp.Points {
fmt.Println(p.GetInterval().GetEndTime().AsTime())
fmt.Println(p.GetValue().GetDoubleValue())
}
}
}
測試
執行印出以下。
2024-03-08 08:06:00 +0000 UTC
0.006187117951367327
2024-03-08 08:05:00 +0000 UTC
0.006291044821911858
2024-03-08 08:04:00 +0000 UTC
0.006011338220667994
2024-03-08 08:03:00 +0000 UTC
0.006441010437955204
2024-03-08 08:02:00 +0000 UTC
0.006379487894865103
2024-03-08 08:01:00 +0000 UTC
0.006521140662723231
2024-03-08 08:00:00 +0000 UTC
0.005556564938605864
沒有留言:
張貼留言