Skip to content

OpenCensus

Jonathan Amsterdam edited this page Jan 4, 2018 · 22 revisions

Google Cloud client libraries provide stats and traces with the use of the OpenCensus instrumentation framework. Stats and trace collection is available from the following packages:

Traces

In order to upload the collected traces, users need to register a trace exporter. OpenCensus provides support for various tracing backends including Stackdriver Trace. See the trace exporters listing to find an exporter for the backend of your choice.

For example, in order to upload traces to Stackdriver Trace, register a trace exporter in your main program. The Stackdriver exporter requires you to enable the Stackdriver Trace API on the Cloud Console and enable ADC for auth.

import (
	"go.opencensus.io/exporter/trace/stackdriver"
	"go.opencensus.io/trace"
)

exporter, err := stackdriver.NewExporter(stackdriver.Options{ProjectID: "google-cloud-project-id"})
if err != nil {
	log.Fatal(err)
}
trace.RegisterExporter(exporter)

Calls can trace an existing span if the provided context contains an OpenCensus span.

import (
	"cloud.google.com/go/spanner"
	"go.opencensus.io/trace"
)

client, err := spanner.NewClient(ctx, "projects/P/instances/I/databases/D")
if err != nil {
    log.Fatal(err)
}
defer client.Close()

ctx = trace.StartSpan(ctx, "foo")
defer trace.EndSpan(ctx)

// Do other work here...

row, err := client.Single().ReadRow(ctx, "Users", spanner.Key{"alice"}, []string{"email"})
if err != nil {
    log.Fatal(err)
}

Stats

OpenCensus automatically collects stats about the gRPC clients (all except for bigquery and storage). In order to collect the recorded stats from the instrumented packages, you need to subscribe to the stats views provided from the gRPC integrations for the gRPC clients.

All available client views are at the grpcstats package.

For example, subscribe to collect client request count:

if err := grpcstats.RPCClientRequestCountView.Subscribe(); err != nil {
	log.Fatal(err)
}

Then, you can use the exporter of your choice to upload the collected stats to a metric collection backend.

As an example, in order to upload data to Stackdriver Monitoring, register the Stackdriver Monitoring exporter in your main program. The Stackdriver exporter requires you to enable the Stackdriver Monitoring API on the Cloud Console and enable ADC for auth.

import (
	"go.opencensus.io/exporter/stats/stackdriver"
	"go.opencensus.io/stats"
)

exporter, err := stackdriver.NewExporter(stackdriver.Options{ProjectID: "google-cloud-project-id"})
if err != nil {
	log.Fatal(err)
}
stats.RegisterExporter(exporter)
Clone this wiki locally