gostackdrivergoogle-cloud-stackdriveropencensus

Custom OpenCensus metrics not appearing on Stackdriver


I'm trying to send custom metrics to Stackdriver from my Go application using OpenCensus.

I've followed the guide, so the views and exporter are setup:

import (
    "context"
    "contrib.go.opencensus.io/exporter/stackdriver"
    "github.com/pkg/errors"
    "go.opencensus.io/stats"
    "go.opencensus.io/stats/view"
    "time"
)

var (
    apiRequestDurationMs = stats.Int64("api_request_duration", "API request duration in milliseconds", stats.UnitMilliseconds)
)

func NewMetricsExporter() (*stackdriver.Exporter, error) {
    v := &view.View{
        Name:        "api_request_durations",
        Measure:     apiRequestDurationMs,
        Description: "The distribution of request durations",
        Aggregation: view.Distribution(0, 100, 200, 400, 1000, 2000, 4000),
    }
    if registerError := view.Register(v); registerError != nil {
        return nil, errors.Wrapf(registerError, "failed to register request duration view")
    }

    exporter, exporterError := stackdriver.NewExporter(stackdriver.Options{ProjectID: "project-ID"})
    if exporterError != nil {
        return nil, errors.Wrapf(exporterError, "failed to create stackdriver exporter")
    }

    if startError := exporter.StartMetricsExporter(); startError != nil {
        return nil, errors.Wrapf(startError, "failed to create stackdriver exporter")

    }
    return exporter, nil
}

And then I send my metrics using:

func RequestDuration(d time.Duration) {
    stats.Record(context.Background(), apiRequestDurationMs.M(int64(d)))
}

But the custom metrics I'm sending aren't appearing in Stackdriver's Metrics Explorer.

What am I missing?


Solution

  • The issue was in the user guide. You must in fact register the exporter and set a reporting interval:

    view.RegisterExporter(exporter)
    view.SetReportingPeriod(60 * time.Second)