Skip to content

Instantly share code, notes, and snippets.

@DazWilkin
Created February 17, 2018 02:38
Show Gist options
  • Save DazWilkin/7c5ba128b806a91dc5022c157a1fb41c to your computer and use it in GitHub Desktop.
Save DazWilkin/7c5ba128b806a91dc5022c157a1fb41c to your computer and use it in GitHub Desktop.
Stackdriver Monitoring API v3 Golang
package main
import (
"context"
"fmt"
"log"
"time"
monitoring "cloud.google.com/go/monitoring/apiv3"
googlepb "github.com/golang/protobuf/ptypes/timestamp"
iterator "google.golang.org/api/iterator"
monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3"
)
const (
metricType = "container.googleapis.com/container/cpu/utilization"
resourceType = "gke_container"
)
func main() {
ctx := context.Background()
client, err := monitoring.NewMetricClient(ctx)
if err != nil {
log.Fatalf("Failed to create client: %v", err)
}
projectID := "[[YOUR-PROJECT]]"
filter := fmt.Sprintf("metric.type=\"%v\" resource.type=\"%v\"",
metricType,
resourceType)
req := monitoringpb.ListTimeSeriesRequest{
Name: fmt.Sprintf("projects/%v", projectID),
Filter: filter,
Interval: &monitoringpb.TimeInterval{
StartTime: &googlepb.Timestamp{
Seconds: time.Now().Add(-time.Hour * 1).Unix()},
EndTime: &googlepb.Timestamp{
Seconds: time.Now().Unix()}}}
it := client.ListTimeSeries(ctx, &req)
for {
timeseries, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
log.Fatalf("Failed to iterate over timeseries: %v", err)
}
fmt.Printf("Metric: %v\n", timeseries.Metric.Type)
for k, v := range timeseries.Metric.Labels {
fmt.Printf("Label: %v=%v\n", k, v)
}
fmt.Printf("Resource: %v\n", timeseries.Resource.Type)
for k, v := range timeseries.Resource.Labels {
fmt.Printf("Label: %v=%v\n", k, v)
}
for _, point := range timeseries.Points {
fmt.Printf("Point: [%v-%v] = %v\n",
point.Interval.StartTime.Seconds,
point.Interval.EndTime.Seconds,
point.GetValue().GetDoubleValue())
}
}
}
@plutov
Copy link

plutov commented Jan 9, 2019

I published the tool to publish Go runtime stats to Stackdriver - https://github.com/plutov/gosd

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment