1// Copyright 2017, OpenCensus Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// Command stackdriver is an example program that collects data for
16// video size. Collected data is exported to
17// Stackdriver Monitoring.
18package main
19
20import (
21	"context"
22	"fmt"
23	"log"
24	"time"
25
26	"contrib.go.opencensus.io/exporter/stackdriver"
27	"contrib.go.opencensus.io/exporter/stackdriver/monitoredresource"
28	"go.opencensus.io/stats"
29	"go.opencensus.io/stats/view"
30)
31
32// Create measures. The program will record measures for the size of
33// processed videos and the nubmer of videos marked as spam.
34var videoSize = stats.Int64("my.org/measure/video_size", "size of processed videos", stats.UnitBytes)
35
36func main() {
37	ctx := context.Background()
38
39	// Collected view data will be reported to Stackdriver Monitoring API
40	// via the Stackdriver exporter.
41	//
42	// In order to use the Stackdriver exporter, enable Stackdriver Monitoring API
43	// at https://console.cloud.google.com/apis/dashboard.
44	//
45	// Once API is enabled, you can use Google Application Default Credentials
46	// to setup the authorization.
47	// See https://developers.google.com/identity/protocols/application-default-credentials
48	// for more details.
49	se, err := stackdriver.NewExporter(stackdriver.Options{
50		ProjectID:         "your-project-id", // Google Cloud Console project ID for stackdriver.
51		MonitoredResource: monitoredresource.Autodetect(),
52	})
53	se.StartMetricsExporter()
54	defer se.StopMetricsExporter()
55
56	if err != nil {
57		log.Fatal(err)
58	}
59
60	// Create view to see the processed video size cumulatively.
61	// Subscribe will allow view data to be exported.
62	// Once no longer need, you can unsubscribe from the view.
63	if err := view.Register(&view.View{
64		Name:        "my.org/views/video_size_cum",
65		Description: "processed video size over time",
66		Measure:     videoSize,
67		Aggregation: view.Distribution(1<<16, 1<<32),
68	}); err != nil {
69		log.Fatalf("Cannot subscribe to the view: %v", err)
70	}
71
72	processVideo(ctx)
73
74	// Wait for a duration longer than reporting duration to ensure the stats
75	// library reports the collected data.
76	fmt.Println("Wait longer than the reporting duration...")
77	time.Sleep(1 * time.Minute)
78}
79
80func processVideo(ctx context.Context) {
81	// Do some processing and record stats.
82	stats.Record(ctx, videoSize.M(25648))
83}
84