-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathexample_test.go
111 lines (94 loc) · 2.43 KB
/
example_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package gmetric_test
import (
"errors"
"github.com/viant/gmetric"
"github.com/viant/gmetric/counter/base"
"github.com/viant/gmetric/stat"
"log"
"math/rand"
"net/http"
"time"
)
func ExampleService_Counter() {
metrics := gmetric.New()
handler := gmetric.NewHandler("/v1/metrics", metrics)
http.Handle("/v1/metrics", handler)
//basic single counter
counter := metrics.OperationCounter("pkg.myapp", "mySingleCounter1", "my description", time.Microsecond, time.Minute, 2)
go runBasicTasks(counter)
go http.ListenAndServe(":8080", http.DefaultServeMux)
}
func runBasicTasks(counter *gmetric.Operation) {
for i := 0; i < 1000; i++ {
runBasicTask(counter)
}
}
func runBasicTask(counter *gmetric.Operation) {
onDone := counter.Begin(time.Now())
defer func() {
onDone(time.Now())
}()
time.Sleep(time.Nanosecond)
}
const (
NoSuchKey = "noSuchKey"
MyStatsCacheHit = "cacheHit"
MyStatsCacheCollision = "cacheCollision"
)
//MultiStateStatTestProvider represents multi stats value provider
type MultiStateStatTestProvider struct{ *base.Provider }
//Map maps value int slice index
func (p *MultiStateStatTestProvider) Map(key interface{}) int {
textKey, ok := key.(string)
if !ok {
return p.Provider.Map(key)
}
switch textKey {
case NoSuchKey:
return 1
case MyStatsCacheHit:
return 2
case MyStatsCacheCollision:
return 3
}
return -1
}
func ExampleService_MultiOperationCounter() {
metrics := gmetric.New()
handler := gmetric.NewHandler("/v1/metrics", metrics)
http.Handle("/v1/metrics", handler)
counter := metrics.MultiOperationCounter("pkg.myapp", "myMultiCounter", "my description", time.Microsecond, time.Minute, 2, &MultiStateStatTestProvider{})
go runMultiStateTasks(counter)
err := http.ListenAndServe(":8080", http.DefaultServeMux)
if err != nil {
log.Fatal(err)
}
}
func runMultiStateTasks(counter *gmetric.Operation) {
for i := 0; i < 1000; i++ {
runMultiStateTask(counter)
}
}
func runMultiStateTask(counter *gmetric.Operation) {
stats := stat.New()
onDone := counter.Begin(time.Now())
defer func() {
onDone(time.Now(), stats)
}()
time.Sleep(time.Nanosecond)
//simulate task metrics state
rnd := rand.NewSource(time.Now().UnixNano())
state := rnd.Int63() % 3
switch state {
case 0:
stats.Append(NoSuchKey)
case 1:
stats.Append(MyStatsCacheHit)
case 2:
stats.Append(MyStatsCacheHit)
stats.Append(MyStatsCacheCollision)
}
if rnd.Int63()%10 == 0 {
stats.Append(errors.New("test error"))
}
}