8 // Config is used to configure metrics settings
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
19 // Metrics represents an instance of a metrics sink that can
27 // Shared global metrics instance
28 var globalMetrics *Metrics
31 // Initialize to a blackhole sink to avoid errors
32 globalMetrics = &Metrics{sink: &BlackholeSink{}}
35 // DefaultConfig provides a sane default configuration
36 func DefaultConfig(serviceName string) *Config {
38 ServiceName: serviceName, // Use client provided service
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
47 // Try to get the hostname
48 name, _ := os.Hostname()
53 // New is used to create a new instance of Metrics
54 func New(conf *Config, sink MetricSink) (*Metrics, error) {
59 // Start the runtime collector
60 if conf.EnableRuntimeMetrics {
66 // NewGlobal is the same as New, but it assigns the metrics object to be
67 // used globally as well as returning it.
68 func NewGlobal(conf *Config, sink MetricSink) (*Metrics, error) {
69 metrics, err := New(conf, sink)
71 globalMetrics = metrics
76 // Proxy all the methods to the globalMetrics instance
77 func SetGauge(key []string, val float32) {
78 globalMetrics.SetGauge(key, val)
81 func EmitKey(key []string, val float32) {
82 globalMetrics.EmitKey(key, val)
85 func IncrCounter(key []string, val float32) {
86 globalMetrics.IncrCounter(key, val)
89 func AddSample(key []string, val float32) {
90 globalMetrics.AddSample(key, val)
93 func MeasureSince(key []string, start time.Time) {
94 globalMetrics.MeasureSince(key, start)