...
1 package test
2
3 import (
4 "context"
5 "fmt"
6
7 "go.opencensus.io/metric"
8 "go.opencensus.io/metric/metricdata"
9 "go.opencensus.io/metric/metricexport"
10 "go.opencensus.io/stats"
11 "go.opencensus.io/stats/view"
12 "go.opencensus.io/tag"
13 )
14
15 var (
16 myTag = tag.MustNewKey("my_label")
17 myMetric = stats.Int64("my_metric", "description", stats.UnitDimensionless)
18 )
19
20 func init() {
21 if err := view.Register(
22 &view.View{
23 Measure: myMetric,
24 TagKeys: []tag.Key{myTag},
25 Aggregation: view.Sum(),
26 },
27 ); err != nil {
28 panic(err)
29 }
30 }
31
32 func ExampleExporter_stats() {
33 metricReader := metricexport.NewReader()
34 metrics := NewExporter(metricReader)
35 metrics.ReadAndExport()
36 metricBase := getCounter(metrics, myMetric.Name(), newMetricKey("label1"))
37
38 for i := 1; i <= 3; i++ {
39
40 stats.RecordWithTags(context.Background(),
41 []tag.Mutator{tag.Upsert(myTag, "label1")},
42 myMetric.M(int64(i)))
43
44
45 metrics.ReadAndExport()
46 metricValue := getCounter(metrics, myMetric.Name(), newMetricKey("label1"))
47 fmt.Printf("increased by %d\n", metricValue-metricBase)
48 }
49
50
51
52
53 }
54
55 type derivedMetric struct {
56 i int64
57 }
58
59 func (m *derivedMetric) ToInt64() int64 {
60 return m.i
61 }
62
63 func ExampleExporter_metric() {
64 metricReader := metricexport.NewReader()
65 metrics := NewExporter(metricReader)
66 m := derivedMetric{}
67 r := metric.NewRegistry()
68 g, _ := r.AddInt64DerivedCumulative("derived", metric.WithLabelKeys(myTag.Name()))
69 g.UpsertEntry(m.ToInt64, metricdata.NewLabelValue("l1"))
70 for i := 1; i <= 3; i++ {
71
72 m.i = int64(i)
73
74
75 metrics.ExportMetrics(context.Background(), r.Read())
76 metricValue := getCounter(metrics, "derived", newMetricKey("l1"))
77 fmt.Println(metricValue)
78 }
79
80
81
82
83 }
84
85 func newMetricKey(v string) map[string]string {
86 return map[string]string{myTag.Name(): v}
87 }
88
89 func getCounter(metrics *Exporter, metricName string, metricKey map[string]string) int64 {
90 p, ok := metrics.GetPoint(metricName, metricKey)
91 if !ok {
92
93 return 0
94 }
95 return p.Value.(int64)
96 }
97
View as plain text