forked from jsteenb2/mess
-
Notifications
You must be signed in to change notification settings - Fork 0
/
svc_observer.go
72 lines (59 loc) · 1.69 KB
/
svc_observer.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
package allsrv
import (
"context"
"time"
"github.com/hashicorp/go-metrics"
"github.com/opentracing/opentracing-go"
)
// ObserveSVC provides a metrics and spanning middleware.
func ObserveSVC(met *metrics.Metrics) func(next SVC) SVC {
return func(next SVC) SVC {
return &svcObserver{
met: met,
next: next,
}
}
}
type svcObserver struct {
met *metrics.Metrics
next SVC
}
func (s *svcObserver) CreateFoo(ctx context.Context, f Foo) (Foo, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "svc_foo_create")
defer span.Finish()
rec := s.record("create")
f, err := s.next.CreateFoo(ctx, f)
return f, rec(err)
}
func (s *svcObserver) ReadFoo(ctx context.Context, id string) (Foo, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "svc_foo_read")
defer span.Finish()
rec := s.record("read")
f, err := s.next.ReadFoo(ctx, id)
return f, rec(err)
}
func (s *svcObserver) UpdateFoo(ctx context.Context, f FooUpd) (Foo, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "svc_foo_update")
defer span.Finish()
rec := s.record("update")
updatedFoo, err := s.next.UpdateFoo(ctx, f)
return updatedFoo, rec(err)
}
func (s *svcObserver) DelFoo(ctx context.Context, id string) error {
span, ctx := opentracing.StartSpanFromContext(ctx, "svc_foo_delete")
defer span.Finish()
rec := s.record("delete")
return rec(s.next.DelFoo(ctx, id))
}
func (s *svcObserver) record(op string) func(error) error {
start := time.Now()
name := []string{metricsPrefix, op}
s.met.IncrCounter(append(name, "reqs"), 1)
return func(err error) error {
if err != nil {
s.met.IncrCounter(append(name, "errs"), 1)
}
s.met.MeasureSince(append(name, "dur"), start)
return err
}
}