-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrunstats.go
115 lines (96 loc) · 2.13 KB
/
runstats.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
112
113
114
115
package runstats
import (
"fmt"
"net"
"os"
"path"
"strconv"
"time"
graphite "github.com/marpaia/graphite-golang"
"github.com/skx/golang-metrics/collector"
)
// Handle to the graphite object
var g *graphite.Graphite
// Should we be verbose?
var verbose bool
// The prefix of all our metrics
var prefix string
func init() {
// Should we be verbose?
v := os.Getenv("METRICS_VERBOSE")
if v != "" {
verbose = true
}
// Do we have a custom prefix?
prefix = os.Getenv("METRICS_PREFIX")
if prefix == "" {
// If not use the default.
prefix = "go." + path.Base(os.Args[0]) + "."
}
// Get the destination to send the metrics to.
host := os.Getenv("METRICS_HOST")
if host == "" {
host = os.Getenv("METRICS")
}
if host == "" {
return
}
var err error
// Split our host-value into Host + Port
h, p, err := net.SplitHostPort(host)
if err != nil {
// If that failed we assume the port was missing
h = host
p = "2003"
}
// port should be an integer
port, err := strconv.Atoi(p)
if err != nil {
fmt.Printf("Error converting port %s to integer: %s\n", p, err.Error())
return
}
//
// We default to UDP, but if `METRICS_PROTOCOL` specifies TCP we
// will use that instead.
//
protocol := os.Getenv("METRICS_PROTOCOL")
if protocol == "" {
protocol = "udp"
}
//
// Create the graphite-object.
//
g, err = graphite.GraphiteFactory(protocol, h, port, "")
if err != nil {
fmt.Printf("Error setting up metrics - skipping - %s\n", err.Error())
return
}
//
// Launch a goroutine to submit metrics on our schedule
//
go runCollector()
}
func runCollector() {
gaugeFunc := func(key string, val uint64) {
if g != nil {
if verbose {
fmt.Printf("%s %d\n", prefix+key, val)
}
g.SimpleSend(prefix+key, strconv.FormatUint(val, 10))
}
}
c := collector.New(gaugeFunc)
//
// A duration might be specified to alter our default
// of ten seconds.
//
if os.Getenv("METRICS_DELAY") != "" {
secs, err := strconv.Atoi(os.Getenv("METRICS_DELAY"))
if err == nil {
c.PauseDur = time.Second * time.Duration(secs)
} else {
fmt.Printf("Error processing $METRICS_DELAY: %s\n", err.Error())
}
}
c.Run()
}