ddstats

package module
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Dec 7, 2020 License: MIT Imports: 10 Imported by: 0

README

DDStats

DDStats is a non-statsd DataDog stats client written in go.

GoDoc Build Status Coverage Status

Example

package main

import (
	"github.com/jmizell/ddstats"
	"log"
)

func main() {

	// Create a config with parameters, or use the FromEnv method to
	// load config from environment variables.
	cfg := ddstats.NewConfig().
		WithNamespace("my-namespace").
		WithHost("myhost.local").
		WithAPIKey("api_key").
		WithTags([]string{"custom_tag:true"})

	// Initialize the client with your namespace, host, api key, and your global tags
	stats, err := ddstats.NewStats(cfg)
	if err != nil {
		log.Fatalf(err.Error())
	}

	// We can add a new metric by calling any of the methods, Increment,
	// Decrement, Count or Gauge. Increment increases a count metric by one.
	stats.Increment("metric1", nil)

	// Custom tags will be combined with the global tags on send to the api.
	stats.Increment("metric2", []string{"tag:1"})

	// Decrement decreases a count metric by 1.
	stats.Decrement("metric1", nil)

	// Count allows you to add an arbitrary value to a count metric.
	stats.Count("metric1", 10, nil)

	// Metrics are unique by name, and tags. Metric1 with nil tags, and
	// metric1 with one custom tag, are stored as two separate values.
	stats.Count("metric1", 10, []string{"tag:1"})

	// Gauge creates a gauge metric. The last value applied to the metric before
	// flush to the api, is the value sent.
	stats.Gauge("metric3", 10, nil)

	// Signal shutdown, and block until complete
	stats.Close()

	// Get a list of errors returned by the api
	if errors := stats.Errors(); len(errors) > 0 {
		for i, err := range errors {
			log.Printf("%d: %s", i, err.Error())
		}
		log.Fatalf("errors were founc")
	}
}

Documentation

Index

Constants

View Source
const (
	DefaultWorkerCount   = 10
	DefaultWorkerBuffer  = 100
	DefaultFlushInterval = time.Second * 60
	DefaultMaxErrorCount = 100
	DefaultNamespace     = "ddstats"
)

Default config values

View Source
const (
	EnvWorkerCount          = "DDSTATS_WORKER_COUNT"
	EnvWorkerBuffer         = "DDSTATS_WORKER_BUFFER"
	EnvMetricBuffer         = "DDSTATS_METRIC_BUFFER"
	EnvFlushIntervalSeconds = "DDSTATS_FLUSH_INTERVAL"
	EnvMaxErrorCount        = "DDSTATS_MAX_ERROR_COUNT"
	EnvNamespace            = "DDSTATS_NAMESPACE"
	EnvHost                 = "DDSTATS_HOST"
	EnvTags                 = "DDSTATS_TAGS"
	EnvAPIKey               = "DDSTATS_API_KEY"
)

Config environment variables

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	Namespace            string   `json:"namespace"`      // Namespace is prepended to the name of every metric
	Host                 string   `json:"host"`           // Host to apply to every metric
	Tags                 []string `json:"tags"`           // A global list of tags to append to metrics
	APIKey               string   `json:"api_key"`        // Datadog API key
	FlushIntervalSeconds float64  `json:"flush_interval"` // Interval in seconds to send metrics to Datadog
	WorkerCount          int      `json:"worker_count"`   // Number of workers to process metrics updates
	WorkerBuffer         int      `json:"worker_buffer"`  // Buffer capacity for worker queue
	MetricBuffer         int      `json:"metric_buffer"`  // Global buffer capacity for new metrics not yet assigned a worker
	MaxErrors            int      `json:"max_errors"`     // Max number of flush errors to store
	// contains filtered or unexported fields
}

Config is required to create an new stats object. A config object can be manually created, initialized with defaults using NewConfig, or sourced from environment variables.

Required

An API client is required in order to use stats. Either the API key must be set, or an API client can be manually created, and added to the config using WithClient.

func NewConfig

func NewConfig() *Config

NewConfig creates a new config with default values. The host value is sourced from os.Hostname().

func (*Config) FromEnv

func (c *Config) FromEnv() *Config

FromEnv loads config properties from environment variables. Existing variables in the config will be overwritten. Environment variables that are not set, or are empty, will be ignored.

Supported variables

DDSTATS_WORKER_COUNT, DDSTATS_WORKER_BUFFER, DDSTATS_METRIC_BUFFER DDSTATS_FLUSH_INTERVAL, DDSTATS_MAX_ERROR_COUNT, DDSTATS_NAMESPACE, DDSTATS_HOST, DDSTATS_TAGS, DDSTATS_API_KEY

func (*Config) WithAPIKey

func (c *Config) WithAPIKey(key string) *Config

WithAPIKey set the api key. Instructions on how to acquire an api key can be found here https://docs.datadoghq.com/account_management/api-app-keys/ If a client has been set with WithClient, then api key will be ignored.

func (*Config) WithClient

func (c *Config) WithClient(client client.APIClient) *Config

WithClient set the api client to use. If api key and client have both been set, the client will be used. If no client has been set, then a client will be created with the api key.

func (*Config) WithHost

func (c *Config) WithHost(Host string) *Config

WithHost sets the host name for ddstats

func (*Config) WithNamespace

func (c *Config) WithNamespace(Namespace string) *Config

WithNamespace set the namespace for ddstats

func (*Config) WithTags

func (c *Config) WithTags(tags []string) *Config

WithTags set global slice of tags

type Stats

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

func NewStats

func NewStats(cfg *Config) (*Stats, error)

func (*Stats) Close

func (c *Stats) Close()

Close signals a shutdown, and blocks while waiting for flush to complete, and all workers to shutdown.

func (*Stats) Count

func (c *Stats) Count(name string, value float64, tags []string)

Count creates or adds a count metric by value. This is a non-blocking method, if the channel buffer is full, then the metric is not recorded. Count stats are sent as count, by taking the sum value of all values in the flush interval.

func (*Stats) Decrement

func (c *Stats) Decrement(name string, tags []string)

Decrement creates or subtracts a count metric by -1. This is a non-blocking method, if the channel buffer is full, then the metric is not recorded. Count stats are sent as count, by taking the sum value of all values in the flush interval.

func (*Stats) DecrementRate added in v1.1.0

func (c *Stats) DecrementRate(name string, tags []string)

DecrementRate creates or subtracts a rate metric by -1. This is a non-blocking method, if the channel buffer is full, then the metric is not recorded. Rate stats are sent as rate, by taking the count value and dividing by the number of seconds since the last flush.

func (*Stats) ErrorCallback

func (c *Stats) ErrorCallback(f func(err error, metricSeries []*client.DDMetric))

ErrorCallback registers a call back function that will be called if any error is returned by the api client during a flush.

func (*Stats) Errors

func (c *Stats) Errors() []error

Errors returns a slice of all errors returned by the api client during a flush.

func (*Stats) Event

func (c *Stats) Event(event *client.DDEvent) error

Event immediately posts an DDEvent to he Datadog api. If host, or namespace vales are missing, the values will be filled before sending to the api. Global tags are appended to the event.

func (*Stats) Flush

func (c *Stats) Flush()

Flush signals the main worker thread to copy all current metrics, and send them to the Datadog api. Flush blocks until all flush jobs complete. been sent, use FlushWait.

func (*Stats) FlushCallback

func (c *Stats) FlushCallback(f func(metricSeries []*client.DDMetric))

FlushCallback registers a call back function that will be called at the end of every successful flush.

func (*Stats) Gauge

func (c *Stats) Gauge(name string, value float64, tags []string)

Gauge creates or updates a gauge metric by value. This is a non-blocking method, if the channel buffer is full, then the metric not recorded. Gauge stats are reported as the last value sent before flush is called.

func (*Stats) GetDroppedMetricCount

func (c *Stats) GetDroppedMetricCount() uint64

GetDroppedMetricCount returns the number off metrics submitted to the metric queue, and where dropped because the queue was full.

func (*Stats) Increment

func (c *Stats) Increment(name string, tags []string)

Increment creates or increments a count metric by +1. This is a non-blocking method, if the channel buffer is full, then the metric is not recorded. Count stats are sent as count, by taking the sum value of all values in the flush interval.

func (*Stats) IncrementRate added in v1.1.0

func (c *Stats) IncrementRate(name string, tags []string)

IncrementRate creates or increments a rate metric by +1. This is a non-blocking method, if the channel buffer is full, then the metric is not recorded. Rate stats are sent as rate, by taking the count value and dividing by the number of seconds since the last flush.

func (*Stats) QueueSeries added in v1.1.0

func (c *Stats) QueueSeries(series []*client.DDMetric)

QueueSeries adds a series of metrics to the queue to be be sent with the next flush.

func (*Stats) Rate added in v1.1.0

func (c *Stats) Rate(name string, value float64, tags []string)

Rate creates or adds a rate metric by value. This is a non-blocking method, if the channel buffer is full, then the metric is not recorded. Rate stats are sent as rate, by taking the count value and dividing by the number of seconds since the last flush.

func (*Stats) SendSeries

func (c *Stats) SendSeries(series []*client.DDMetric) error

SendSeries immediately posts an DDMetric series to the Datadog api. Each metric in the series is checked for an host name, and the correct namespace. If host, or namespace vales are missing, the values will be filled before sending to the api. Global tags are added to all metrics.

func (*Stats) ServiceCheck

func (c *Stats) ServiceCheck(check, message string, status client.Status, tags []string) error

ServiceCheck immediately posts an DDServiceCheck to he Datadog api. The namespace is prepended to the check name, if it is missing. Host, and time is automatically added. Global tags are appended to tags passed to the method.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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