Skip to content

Commit

Permalink
Add collector based example for metric export (#657)
Browse files Browse the repository at this point in the history
* Fix dashboard config

* Add collector based example

* Update collector config

* Udpate README

* Updates chart image to reflect new UI

* Update gitignore

* Remove go.mod from a non-module directory

* Fix linter errors

* Remove file and logging exporters from sample config

* Fix linter errors
  • Loading branch information
psx95 committed Jul 7, 2023
1 parent cc91e37 commit a19d9ea
Show file tree
Hide file tree
Showing 11 changed files with 701 additions and 11 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Expand Up @@ -9,4 +9,5 @@ Thumbs.db
*.so
coverage.*

/example/metric/metric
/example/metric/collector/metrics
/example/metric/sdk/metrics
10 changes: 9 additions & 1 deletion example/metric/README.md
Expand Up @@ -22,7 +22,11 @@ Next, set this project ID to the environment variable `GOOGLE_PROJECT_ID` using
export GOOGLE_PROJECT_ID=$(gcloud config get-value project)
```

Once you ensure the API is enabled, then build the example application and run the executable.
Once you ensure the API is enabled, then build the example application and run the executable. There are two separate examples showcasing the following -
1. Exporting metrics via the SDK.
2. Exporting metrics via the OpenTelemetry Collector.

Change the current directory to the example you wish to run - either to [sdk](./sdk/) directory or [collector](./collector/) directory and then run the example using following commands:

```
$ go build -o metrics
Expand All @@ -36,6 +40,8 @@ $ ./metrics

To ensure you have enough data to create interesting charts for the Counter and Observer metrics generated by the example, keep the application running for at least five minutes.

*Note: For running the collector example, you need to have a locally running OpenTelemetry Collector, configured using the provided [sample config](./collector/sample-collector-config.yaml). Instructions for running OpenTelemetry Collector on your system can be found [here](https://opentelemetry.io/docs/collector/getting-started/#local).*

## Create dashboard

https://console.cloud.google.com/monitoring/dashboards?project=<your-project-id>
Expand All @@ -54,4 +60,6 @@ This script creates a dashboard titled "OpenTelemetry exporter example/metric".

You should be able to view line charts like below once you create the dashboard.

*Note: This script is configured to create dashboard which displays the metrics generated via the `sdk` example.*

<img width="1200" alt="2 charts in dashboard" src="images/charts.png?raw=true"/>
167 changes: 167 additions & 0 deletions example/metric/collector/example.go
@@ -0,0 +1,167 @@
// Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
"context"
"log"
"math/rand"
"sync"
"time"

"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp"

"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/metric"
sdkmetric "go.opentelemetry.io/otel/sdk/metric"
)

type observedFloat struct {
mu sync.RWMutex
f float64
}

func (of *observedFloat) set(v float64) {
of.mu.Lock()
defer of.mu.Unlock()
of.f = v
}

func (of *observedFloat) get() float64 {
of.mu.RLock()
defer of.mu.RUnlock()
return of.f
}

func newObservedFloat(v float64) *observedFloat {
return &observedFloat{
f: v,
}
}

type observedInt struct {
mu sync.RWMutex
i int64
}

func (oi *observedInt) set(v int64) {
oi.mu.Lock()
defer oi.mu.Unlock()
oi.i = v
}

func (oi *observedInt) get() int64 {
oi.mu.RLock()
defer oi.mu.RUnlock()
return oi.i
}

func newObservedInt(v int64) *observedInt {
return &observedInt{
i: v,
}
}

// Export OTLP metrtics using the otlpmetrichttp exporter.
// This example is used to demostrate how to use the collector approach to export metrics to Google Cloud.
func main() {
ctx := context.Background()
exp, err := otlpmetrichttp.New(ctx, otlpmetrichttp.WithInsecure())
if err != nil {
panic(err)
}

// initialize a MeterProvider with that periodically exports to the otlp exporter.
provider := sdkmetric.NewMeterProvider(
sdkmetric.WithReader(sdkmetric.NewPeriodicReader(exp)),
)
defer func() {
if err = provider.Shutdown(ctx); err != nil {
log.Fatalf("failed to shutdown meter provider: %v", err)
}
}()

// Create a meter with which we will record metrics for our package.
meter := provider.Meter("github.com/GoogleCloudPlatform/opentelemetry-operations-go/example/collector/metric")

// Register counter value
counter, err := meter.Int64Counter("counter-a-collector")
if err != nil {
log.Fatalf("Failed to create counter: %v", err)
}
clabels := []attribute.KeyValue{attribute.Key("key").String("value")}
counter.Add(ctx, 100, metric.WithAttributes(clabels...))

histogram, err := meter.Float64Histogram("histogram-b-collector")
if err != nil {
log.Fatalf("Failed to create histogram: %v", err)
}

// Register observer value
olabels := []attribute.KeyValue{
attribute.String("foo", "Tokyo"),
attribute.String("bar", "Sushi"),
}
of := newObservedFloat(12.34)

gaugeObserver, err := meter.Float64ObservableGauge("observer-a-collector")
if err != nil {
log.Fatalf("failed to initialize instrument: %v", err)
}
_, err = meter.RegisterCallback(func(ctx context.Context, o metric.Observer) error {
v := of.get()
o.ObserveFloat64(gaugeObserver, v, metric.WithAttributes(olabels...))
return nil
}, gaugeObserver)
if err != nil {
log.Fatalf("failed to register callback: %v", err)
}

oi := newObservedInt(3)
// Export boolean as a custom type (Boolean types are not supported in OTLP)
gaugeObserverBool, err := meter.Int64ObservableGauge("observer-boolean-collector", metric.WithUnit("{gcp.BOOL}"))
if err != nil {
log.Fatalf("failed to initialize instrument: %v", err)
}
_, err = meter.RegisterCallback(func(ctx context.Context, o metric.Observer) error {
v := oi.get()
o.ObserveInt64(gaugeObserverBool, v, metric.WithAttributes(clabels...))
return nil
}, gaugeObserverBool)
if err != nil {
log.Fatalf("failed to register callback: %v", err)
}

// Add measurement once an every 10 second.
timer := time.NewTicker(10 * time.Second)
rng := rand.New(rand.NewSource(time.Now().UnixNano()))
for range timer.C {
r := rng.Int63n(100)
cv := 100 + r
counter.Add(ctx, cv, metric.WithAttributes(clabels...))

r2 := rng.Int63n(100)
hv := float64(r2) / 20.0
histogram.Record(ctx, hv, metric.WithAttributes(clabels...))
ovf := 12.34 + hv
of.set(ovf)

r3 := rng.Int63n(2) // 0 or 1
ovi := int64(r3)
oi.set(ovi)

log.Printf("Most recent data: counter %v, observer-float %v; observer-int %v; histogram %v", cv, ovf, ovi, hv)
}
}
29 changes: 29 additions & 0 deletions example/metric/collector/go.mod
@@ -0,0 +1,29 @@
module github.com/GoogleCloudPlatform/opentelemetry-operations-go/example/metric/collector

go 1.20

require (
go.opentelemetry.io/otel v1.16.0
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v0.39.0
go.opentelemetry.io/otel/metric v1.16.0
go.opentelemetry.io/otel/sdk/metric v0.39.0
)

require (
github.com/cenkalti/backoff/v4 v4.2.1 // indirect
github.com/go-logr/logr v1.2.4 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/golang/protobuf v1.5.3 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.7.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.16.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlpmetric v0.39.0 // indirect
go.opentelemetry.io/otel/sdk v1.16.0 // indirect
go.opentelemetry.io/otel/trace v1.16.0 // indirect
go.opentelemetry.io/proto/otlp v0.19.0 // indirect
golang.org/x/net v0.8.0 // indirect
golang.org/x/sys v0.8.0 // indirect
golang.org/x/text v0.8.0 // indirect
google.golang.org/genproto v0.0.0-20230306155012-7f2fa6fef1f4 // indirect
google.golang.org/grpc v1.55.0 // indirect
google.golang.org/protobuf v1.30.0 // indirect
)

0 comments on commit a19d9ea

Please sign in to comment.