blob: 44113f100426b29928ddb8ece15e1b2d97d0ce41 [file] [log] [blame]
khenaidooac637102019-01-14 15:44:34 -05001package metrics
2
3import (
4 "os"
5 "time"
6)
7
8// Config is used to configure metrics settings
9type Config struct {
10 ServiceName string // Prefixed with keys to seperate services
11 HostName string // Hostname to use. If not provided and EnableHostname, it will be os.Hostname
12 EnableHostname bool // Enable prefixing gauge values with hostname
13 EnableRuntimeMetrics bool // Enables profiling of runtime metrics (GC, Goroutines, Memory)
14 EnableTypePrefix bool // Prefixes key with a type ("counter", "gauge", "timer")
15 TimerGranularity time.Duration // Granularity of timers.
16 ProfileInterval time.Duration // Interval to profile runtime metrics
17}
18
19// Metrics represents an instance of a metrics sink that can
20// be used to emit
21type Metrics struct {
22 Config
23 lastNumGC uint32
24 sink MetricSink
25}
26
27// Shared global metrics instance
28var globalMetrics *Metrics
29
30func init() {
31 // Initialize to a blackhole sink to avoid errors
32 globalMetrics = &Metrics{sink: &BlackholeSink{}}
33}
34
35// DefaultConfig provides a sane default configuration
36func DefaultConfig(serviceName string) *Config {
37 c := &Config{
38 ServiceName: serviceName, // Use client provided service
39 HostName: "",
40 EnableHostname: true, // Enable hostname prefix
41 EnableRuntimeMetrics: true, // Enable runtime profiling
42 EnableTypePrefix: false, // Disable type prefix
43 TimerGranularity: time.Millisecond, // Timers are in milliseconds
44 ProfileInterval: time.Second, // Poll runtime every second
45 }
46
47 // Try to get the hostname
48 name, _ := os.Hostname()
49 c.HostName = name
50 return c
51}
52
53// New is used to create a new instance of Metrics
54func New(conf *Config, sink MetricSink) (*Metrics, error) {
55 met := &Metrics{}
56 met.Config = *conf
57 met.sink = sink
58
59 // Start the runtime collector
60 if conf.EnableRuntimeMetrics {
61 go met.collectStats()
62 }
63 return met, nil
64}
65
66// NewGlobal is the same as New, but it assigns the metrics object to be
67// used globally as well as returning it.
68func NewGlobal(conf *Config, sink MetricSink) (*Metrics, error) {
69 metrics, err := New(conf, sink)
70 if err == nil {
71 globalMetrics = metrics
72 }
73 return metrics, err
74}
75
76// Proxy all the methods to the globalMetrics instance
77func SetGauge(key []string, val float32) {
78 globalMetrics.SetGauge(key, val)
79}
80
81func EmitKey(key []string, val float32) {
82 globalMetrics.EmitKey(key, val)
83}
84
85func IncrCounter(key []string, val float32) {
86 globalMetrics.IncrCounter(key, val)
87}
88
89func AddSample(key []string, val float32) {
90 globalMetrics.AddSample(key, val)
91}
92
93func MeasureSince(key []string, start time.Time) {
94 globalMetrics.MeasureSince(key, start)
95}