Go以Google Cloud Client Libraries for Go來取得GCP Cloud Monitoring的metric descriptor。
事前要求
參考「Golang 建立GCP Monitoring Metric Client」建立monitoring.MetricClient
。
取得Metric descriptor
呼叫monitoring.MetricClient.GetMetricDescriptor
,輸入參數monitoringpb.GetMetricDescriptorRequest
取得metric.MetricDescriptor
。
參數monitoringpb.GetMetricDescriptorRequest.Name
的格式為projects/[PROJECT_ID]/metricDescriptors/[METRIC_ID]
,[METRIC_ID]
為Metric type的識別名稱,例如instance CPU utilization指標的識別名稱為compute.googleapis.com/instance/cpu/utilization
(compute下的指標名稱前都要加上前綴compute.googleapis.com/
)。
main.go
package main
import (
"context"
"fmt"
monitoring "cloud.google.com/go/monitoring/apiv3/v2"
"cloud.google.com/go/monitoring/apiv3/v2/monitoringpb"
)
func main() {
ctx := context.Background()
c, err := monitoring.NewMetricClient(ctx)
if err != nil {
panic(err)
}
defer c.Close()
projectId := "project-id-1"
metricId := "compute.googleapis.com/instance/cpu/utilization"
name := fmt.Sprintf("projects/%s/metricDescriptors/%s", projectId, metricId)
md, err := c.GetMetricDescriptor(ctx, &monitoringpb.GetMetricDescriptorRequest{
Name: name,
})
if err != nil {
panic(err)
}
fmt.Println(md.GetName()) // projects/project-id-1/metricDescriptors/compute.googleapis.com/instance/cpu/utilization
fmt.Println(md.GetType()) // compute.googleapis.com/instance/cpu/utilization
fmt.Println(md.GetDisplayName()) // CPU utilization
fmt.Println(md.GetMetricKind()) // GAUGE
fmt.Println(md.GetValueType()) // DOUBLE
fmt.Println(md.GetUnit()) // 10^2.%
fmt.Println(md.GetMonitoredResourceTypes()) // [gce_instance]
fmt.Println(md.GetDescription()) // Fractional utilization of allocated CPU on this instance. Values are...
fmt.Println(md.GetLabels()) // [key:"instance_name" description:"The name of the VM instance."]
}
測試
執行印出以下。
projects/project-id-1/metricDescriptors/compute.googleapis.com/instance/cpu/utilization
compute.googleapis.com/instance/cpu/utilization
CPU utilization
GAUGE
DOUBLE
10^2.%
[gce_instance]
Fractional utilization of allocated CPU on this instance. Values are typically numbers between 0.0 and 1.0 (but some machine types allow bursting above 1.0). Charts display the values as a percentage between 0% and 100% (or more). This metric is reported by the hypervisor for the VM and can differ from `agent.googleapis.com/cpu/utilization`, which is reported from inside the VM.
[key:"instance_name" description:"The name of the VM instance."]
沒有留言:
張貼留言