circonusgometrics

package module
v2.3.1+incompatible Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 16, 2019 License: BSD-3-Clause Imports: 19 Imported by: 68

README

Circonus metrics tracking for Go applications

This library supports named counters, gauges and histograms. It also provides convenience wrappers for registering latency instrumented functions with Go's builtin http server.

Initializing only requires setting an API Token at a minimum.

Options

See OPTIONS.md for information on all of the available cgm options.

Example

Bare bones minimum

A working cut-n-past example. Simply set the required environment variable CIRCONUS_API_TOKEN and run.

package main

import (
    "log"
    "math/rand"
    "os"
    "os/signal"
    "syscall"
    "time"

    cgm "github.com/circonus-labs/circonus-gometrics"
)

func main() {

    logger := log.New(os.Stdout, "", log.LstdFlags)

    logger.Println("Configuring cgm")

    cmc := &cgm.Config{}
    cmc.Debug = false // set to true for debug messages
    cmc.Log = logger

    // Circonus API Token key (https://login.circonus.com/user/tokens)
    cmc.CheckManager.API.TokenKey = os.Getenv("CIRCONUS_API_TOKEN")

    logger.Println("Creating new cgm instance")

    metrics, err := cgm.NewCirconusMetrics(cmc)
    if err != nil {
        logger.Println(err)
        os.Exit(1)
    }

    src := rand.NewSource(time.Now().UnixNano())
    rnd := rand.New(src)

    logger.Println("Adding ctrl-c trap")
    c := make(chan os.Signal, 2)
    signal.Notify(c, os.Interrupt, syscall.SIGTERM)
    go func() {
        <-c
        logger.Println("Received CTRL-C, flushing outstanding metrics before exit")
        metrics.Flush()
        os.Exit(0)
    }()

    logger.Println("Starting to send metrics")

    // number of "sets" of metrics to send
    max := 60

    for i := 1; i < max; i++ {
        logger.Printf("\tmetric set %d of %d", i, 60)
        metrics.Timing("foo", rnd.Float64()*10)
        metrics.Increment("bar")
        metrics.Gauge("baz", 10)
        time.Sleep(time.Second)
    }

    metrics.SetText("fini", "complete")

    logger.Println("Flushing any outstanding metrics manually")
    metrics.Flush()
}
A more complete example

A working, cut-n-paste example with all options available for modification. Also, demonstrates metric tagging.

package main

import (
    "log"
    "math/rand"
    "os"
    "os/signal"
    "syscall"
    "time"

    cgm "github.com/circonus-labs/circonus-gometrics"
)

func main() {

    logger := log.New(os.Stdout, "", log.LstdFlags)

    logger.Println("Configuring cgm")

    cmc := &cgm.Config{}

    // General

    cmc.Interval = "10s"
    cmc.Log = logger
    cmc.Debug = false
    cmc.ResetCounters = "true"
    cmc.ResetGauges = "true"
    cmc.ResetHistograms = "true"
    cmc.ResetText = "true"

    // Circonus API configuration options
    cmc.CheckManager.API.TokenKey = os.Getenv("CIRCONUS_API_TOKEN")
    cmc.CheckManager.API.TokenApp = os.Getenv("CIRCONUS_API_APP")
    cmc.CheckManager.API.URL = os.Getenv("CIRCONUS_API_URL")
    cmc.CheckManager.API.TLSConfig = nil

    // Check configuration options
    cmc.CheckManager.Check.SubmissionURL = os.Getenv("CIRCONUS_SUBMISSION_URL")
    cmc.CheckManager.Check.ID = os.Getenv("CIRCONUS_CHECK_ID")
    cmc.CheckManager.Check.InstanceID = ""
    cmc.CheckManager.Check.DisplayName = ""
    cmc.CheckManager.Check.TargetHost = ""
    //  if hn, err := os.Hostname(); err == nil {
    //      cmc.CheckManager.Check.TargetHost = hn
    //  }
    cmc.CheckManager.Check.SearchTag = ""
    cmc.CheckManager.Check.Secret = ""
    cmc.CheckManager.Check.Tags = ""
    cmc.CheckManager.Check.MaxURLAge = "5m"
    cmc.CheckManager.Check.ForceMetricActivation = "false"

    // Broker configuration options
    cmc.CheckManager.Broker.ID = ""
    cmc.CheckManager.Broker.SelectTag = ""
    cmc.CheckManager.Broker.MaxResponseTime = "500ms"
    cmc.CheckManager.Broker.TLSConfig = nil

    logger.Println("Creating new cgm instance")

    metrics, err := cgm.NewCirconusMetrics(cmc)
    if err != nil {
        logger.Println(err)
        os.Exit(1)
    }

    src := rand.NewSource(time.Now().UnixNano())
    rnd := rand.New(src)

    logger.Println("Adding ctrl-c trap")
    c := make(chan os.Signal, 2)
    signal.Notify(c, os.Interrupt, syscall.SIGTERM)
    go func() {
        <-c
        logger.Println("Received CTRL-C, flushing outstanding metrics before exit")
        metrics.Flush()
        os.Exit(0)
    }()

    // Add metric tags (append to any existing tags on specified metric)
    metrics.AddMetricTags("foo", []string{"cgm:test"})
    metrics.AddMetricTags("baz", []string{"cgm:test"})

    logger.Println("Starting to send metrics")

    // number of "sets" of metrics to send
    max := 60

    for i := 1; i < max; i++ {
        logger.Printf("\tmetric set %d of %d", i, 60)

        metrics.Timing("foo", rnd.Float64()*10)
        metrics.Increment("bar")
        metrics.Gauge("baz", 10)

        if i == 35 {
            // Set metric tags (overwrite current tags on specified metric)
            metrics.SetMetricTags("baz", []string{"cgm:reset_test", "cgm:test2"})
        }

        time.Sleep(time.Second)
    }

    logger.Println("Flushing any outstanding metrics manually")
    metrics.Flush()

}
HTTP Handler wrapping
http.HandleFunc("/", metrics.TrackHTTPLatency("/", handler_func))
HTTP latency example
package main

import (
    "os"
    "fmt"
    "net/http"
    cgm "github.com/circonus-labs/circonus-gometrics"
)

func main() {
    cmc := &cgm.Config{}
    cmc.CheckManager.API.TokenKey = os.Getenv("CIRCONUS_API_TOKEN")

    metrics, err := cgm.NewCirconusMetrics(cmc)
    if err != nil {
        panic(err)
    }

    http.HandleFunc("/", metrics.TrackHTTPLatency("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello, %s!", r.URL.Path[1:])
    }))
    http.ListenAndServe(":8080", http.DefaultServeMux)
}

Unless otherwise noted, the source files are distributed under the BSD-style license found in the LICENSE file.

Documentation

Overview

Package circonusgometrics provides instrumentation for your applications in the form of counters, gauges and histograms and allows you to publish them to Circonus

Counters

A counter is a monotonically-increasing, unsigned, 64-bit integer used to represent the number of times an event has occurred. By tracking the deltas between measurements of a counter over intervals of time, an aggregation layer can derive rates, acceleration, etc.

Gauges

A gauge returns instantaneous measurements of something using signed, 64-bit integers. This value does not need to be monotonic.

Histograms

A histogram tracks the distribution of a stream of values (e.g. the number of seconds it takes to handle requests). Circonus can calculate complex analytics on these.

Reporting

A period push to a Circonus httptrap is confgurable.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CirconusMetrics

type CirconusMetrics struct {
	Log   *log.Logger
	Debug bool
	// contains filtered or unexported fields
}

CirconusMetrics state

func New

func New(cfg *Config) (*CirconusMetrics, error)

New returns a CirconusMetrics instance

func NewCirconusMetrics

func NewCirconusMetrics(cfg *Config) (*CirconusMetrics, error)

NewCirconusMetrics returns a CirconusMetrics instance

func (*CirconusMetrics) Add

func (m *CirconusMetrics) Add(metric string, val uint64)

Add updates counter by supplied value

func (*CirconusMetrics) AddGauge

func (m *CirconusMetrics) AddGauge(metric string, val interface{})

AddGauge adds value to existing gauge

func (*CirconusMetrics) AddMetricTags

func (m *CirconusMetrics) AddMetricTags(name string, tags []string) bool

AddMetricTags appends tags to any existing tags for the named metric and flags a check update is needed

func (*CirconusMetrics) Flush

func (m *CirconusMetrics) Flush()

Flush metrics kicks off the process of sending metrics to Circonus

func (*CirconusMetrics) FlushMetrics added in v1.1.0

func (m *CirconusMetrics) FlushMetrics() *Metrics

FlushMetrics flushes current metrics to a structure and returns it (does NOT send to Circonus)

func (*CirconusMetrics) Gauge

func (m *CirconusMetrics) Gauge(metric string, val interface{})

Gauge sets a gauge to a value

func (*CirconusMetrics) GetCounterTest added in v1.0.0

func (m *CirconusMetrics) GetCounterTest(metric string) (uint64, error)

GetCounterTest returns the current value for a counter. (note: it is a function specifically for "testing", disable automatic submission during testing.)

func (*CirconusMetrics) GetGaugeTest added in v1.0.0

func (m *CirconusMetrics) GetGaugeTest(metric string) (interface{}, error)

GetGaugeTest returns the current value for a gauge. (note: it is a function specifically for "testing", disable automatic submission during testing.)

func (*CirconusMetrics) GetHistogramTest added in v1.0.0

func (m *CirconusMetrics) GetHistogramTest(metric string) ([]string, error)

GetHistogramTest returns the current value for a gauge. (note: it is a function specifically for "testing", disable automatic submission during testing.)

func (*CirconusMetrics) Increment

func (m *CirconusMetrics) Increment(metric string)

Increment counter by 1

func (*CirconusMetrics) IncrementByValue

func (m *CirconusMetrics) IncrementByValue(metric string, val uint64)

IncrementByValue updates counter by supplied value

func (*CirconusMetrics) NewHistogram

func (m *CirconusMetrics) NewHistogram(metric string) *Histogram

NewHistogram returns a histogram instance.

func (*CirconusMetrics) PromOutput

func (m *CirconusMetrics) PromOutput() (*bytes.Buffer, error)

PromOutput returns lines of metrics in prom format

func (*CirconusMetrics) Ready

func (m *CirconusMetrics) Ready() bool

Ready returns true or false indicating if the check is ready to accept metrics

func (*CirconusMetrics) RecordCountForValue

func (m *CirconusMetrics) RecordCountForValue(metric string, val float64, n int64)

RecordCountForValue adds count n for value to a histogram

func (*CirconusMetrics) RecordValue

func (m *CirconusMetrics) RecordValue(metric string, val float64)

RecordValue adds a value to a histogram

func (*CirconusMetrics) RemoveCounter

func (m *CirconusMetrics) RemoveCounter(metric string)

RemoveCounter removes the named counter

func (*CirconusMetrics) RemoveCounterFunc

func (m *CirconusMetrics) RemoveCounterFunc(metric string)

RemoveCounterFunc removes the named counter function

func (*CirconusMetrics) RemoveGauge

func (m *CirconusMetrics) RemoveGauge(metric string)

RemoveGauge removes a gauge

func (*CirconusMetrics) RemoveGaugeFunc

func (m *CirconusMetrics) RemoveGaugeFunc(metric string)

RemoveGaugeFunc removes a gauge function

func (*CirconusMetrics) RemoveHistogram

func (m *CirconusMetrics) RemoveHistogram(metric string)

RemoveHistogram removes a histogram

func (*CirconusMetrics) RemoveText

func (m *CirconusMetrics) RemoveText(metric string)

RemoveText removes a text metric

func (*CirconusMetrics) RemoveTextFunc

func (m *CirconusMetrics) RemoveTextFunc(metric string)

RemoveTextFunc a text metric function

func (*CirconusMetrics) Reset

func (m *CirconusMetrics) Reset()

Reset removes all existing counters and gauges.

func (*CirconusMetrics) Set

func (m *CirconusMetrics) Set(metric string, val uint64)

Set a counter to specific value

func (*CirconusMetrics) SetCounterFunc

func (m *CirconusMetrics) SetCounterFunc(metric string, fn func() uint64)

SetCounterFunc set counter to a function [called at flush interval]

func (*CirconusMetrics) SetGauge

func (m *CirconusMetrics) SetGauge(metric string, val interface{})

SetGauge sets a gauge to a value

func (*CirconusMetrics) SetGaugeFunc

func (m *CirconusMetrics) SetGaugeFunc(metric string, fn func() int64)

SetGaugeFunc sets a gauge to a function [called at flush interval]

func (*CirconusMetrics) SetHistogramValue

func (m *CirconusMetrics) SetHistogramValue(metric string, val float64)

SetHistogramValue adds a value to a histogram

func (*CirconusMetrics) SetMetricTags

func (m *CirconusMetrics) SetMetricTags(name string, tags []string) bool

SetMetricTags sets the tags for the named metric and flags a check update is needed

func (*CirconusMetrics) SetText

func (m *CirconusMetrics) SetText(metric string, val string)

SetText sets a text metric

func (*CirconusMetrics) SetTextFunc

func (m *CirconusMetrics) SetTextFunc(metric string, fn func() string)

SetTextFunc sets a text metric to a function [called at flush interval]

func (*CirconusMetrics) SetTextValue

func (m *CirconusMetrics) SetTextValue(metric string, val string)

SetTextValue sets a text metric

func (*CirconusMetrics) Start

func (m *CirconusMetrics) Start()

Start deprecated NOP, automatic flush is started in New if flush interval > 0.

func (*CirconusMetrics) Timing

func (m *CirconusMetrics) Timing(metric string, val float64)

Timing adds a value to a histogram

func (*CirconusMetrics) TrackHTTPLatency

func (m *CirconusMetrics) TrackHTTPLatency(name string, handler func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request)

TrackHTTPLatency wraps Handler functions registered with an http.ServerMux tracking latencies. Metrics are of the for go`HTTP`<method>`<name>`latency and are tracked in a histogram in units of seconds (as a float64) providing nanosecond ganularity.

type Config

type Config struct {
	Log             *log.Logger
	Debug           bool
	ResetCounters   string // reset/delete counters on flush (default true)
	ResetGauges     string // reset/delete gauges on flush (default true)
	ResetHistograms string // reset/delete histograms on flush (default true)
	ResetText       string // reset/delete text on flush (default true)

	// API, Check and Broker configuration options
	CheckManager checkmgr.Config

	// how frequenly to submit metrics to Circonus, default 10 seconds.
	// Set to 0 to disable automatic flushes and call Flush manually.
	Interval string
}

Config options for circonus-gometrics

type Histogram

type Histogram struct {
	// contains filtered or unexported fields
}

Histogram measures the distribution of a stream of values.

func (*Histogram) Name

func (h *Histogram) Name() string

Name returns the name from a histogram instance

func (*Histogram) RecordValue

func (h *Histogram) RecordValue(v float64)

RecordValue records the given value to a histogram instance

type Metric added in v1.1.0

type Metric struct {
	Type  string      `json:"_type"`
	Value interface{} `json:"_value"`
}

Metric defines an individual metric

type Metrics added in v1.1.0

type Metrics map[string]Metric

Metrics holds host metrics

Directories

Path Synopsis
api
Package api provides methods for interacting with the Circonus API.
Package api provides methods for interacting with the Circonus API.
Package checkmgr provides a check management interface to circonus-gometrics
Package checkmgr provides a check management interface to circonus-gometrics

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL