Help us shape the future of Go! Take the 2026 Go Developer Survey

cloudwatch

package
v0.10.154 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2026 License: MIT Imports: 15 Imported by: 1

Documentation

Overview

Package cloudwatch provides a metrics.Sink that publishes to AWS CloudWatch.

A Sink aggregates emissions in memory and flushes them with PutMetricData on the interval configured by Config.PublishInterval. Aggregation avoids one API call per emission, which CloudWatch bills per request.

Mapping from the metrics package:

  • SetGauge -> MetricDatum.Value, last value wins
  • IncrCounter -> MetricDatum.Value, accumulated
  • AddSample -> MetricDatum.StatisticValues (min/max/sum/count)

Tags become CloudWatch dimensions, up to the 30 that CloudWatch accepts; the extra ones are dropped and reported. Metric names are published verbatim; unlike the Prometheus sink no character replacement is applied.

Lifecycle

NewSink only builds the client. Call Sink.Run in its own goroutine to start the publish loop, and cancel its context to stop it: Sink.Run publishes the last interval before returning. Sink.Flush publishes on demand.

sink, err := cloudwatch.NewSink(&cloudwatch.Config{
	AwsRegion:       "us-west-2",
	Namespace:       "billing",
	PublishInterval: time.Minute,
	MetricsExpiry:   time.Hour,
	WithSampleCount: true,
	WithCleanup:     true,
})
if err != nil {
	return err
}
go sink.Run(ctx)
if _, err := metrics.NewGlobal(cfg, sink); err != nil {
	return err
}

Retention

With Config.WithCleanup the aggregated values are dropped once published, so each datum reports the activity of one publish interval. Without it, values keep accumulating and every flush republishes the running total until Config.MetricsExpiry elapses without an update. Prefer WithCleanup unless a consumer depends on the cumulative shape.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// AwsRegion is the required AWS Region to use.
	// Falls back to the AWS_REGION and AWS_DEFAULT_REGION environment variables.
	AwsRegion string

	// AwsEndpoint is the optional AWS endpoint to use,
	// for example a local CloudWatch emulator.
	AwsEndpoint string

	// Namespace specifies the namespace under which metrics should be published.
	// It is required.
	Namespace string

	// PublishInterval specifies the frequency with which metrics should be published to Cloudwatch.
	// Defaults to 30s.
	PublishInterval time.Duration

	// MetricsExpiry is the period after which the metrics will be deleted from reporting if not used.
	// Defaults to 60m.
	MetricsExpiry time.Duration

	// WithSampleCount specifies to create additional _count, _sum and _avg metrics for sample
	WithSampleCount bool

	// WithCleanup specifies to clean up published metrics,
	// so each publish reports only the activity of the last interval.
	WithCleanup bool
}

Config defines configuration options

type Publisher added in v0.4.0

type Publisher interface {
	PutMetricData(ctx context.Context, params *cloudwatch.PutMetricDataInput, optFns ...func(*cloudwatch.Options)) (*cloudwatch.PutMetricDataOutput, error)
}

Publisher provides interface to publish metrics. It is the subset of the CloudWatch client the Sink uses, so tests and wrappers can substitute their own implementation.

type Sink

type Sink struct {
	// Publisher is the CloudWatch client used to publish.
	// Replace it before Run is started to publish through a custom client.
	Publisher
	// contains filtered or unexported fields
}

Sink provides a metrics.Sink that publishes to AWS CloudWatch.

Emissions are aggregated in memory and sent by Run or Flush. It is safe for concurrent emission.

func NewSink

func NewSink(c *Config) (*Sink, error)

NewSink initializes and returns a pointer to a CloudWatch Sink using the supplied configuration, or an error if there is a problem with the configuration.

PublishInterval and MetricsExpiry fall back to their defaults when they are not positive. It only builds the client; call Run to start publishing.

func (*Sink) AddSample

func (p *Sink) AddSample(key string, val float64, tags []metrics.Tag)

AddSample records an observation into the statistic set (min, max, sum, count) published for the metric.

Individual values are not retained, so CloudWatch reports Minimum, Maximum, Sum, SampleCount and Average for the metric, but cannot compute percentiles from it. Set Config.WithSampleCount to publish the count, sum and average as metrics of their own.

func (*Sink) Data

func (p *Sink) Data() []types.MetricDatum

Data returns collected metrics and allows us to enforce our expiration logic to clean up ephemeral metrics if their value haven't been set for a duration exceeding our allowed expiration time.

When Config.WithSampleCount is set, each sample also yields _count, _sum and _avg metrics. When Config.WithCleanup is set, the returned data is removed from the sink. The returned data is a deep copy: it shares nothing with the sink, so it stays stable while Publish serializes it and other goroutines keep emitting, and a caller may modify it freely.

func (*Sink) Flush

func (p *Sink) Flush(ctx context.Context) error

Flush publishes the aggregated data to CloudWatch, in batches of at most maxMetricsPerRequest data items.

func (*Sink) IncrCounter

func (p *Sink) IncrCounter(key string, val float64, tags []metrics.Tag)

IncrCounter accumulates values until they are published.

func (*Sink) Publish added in v0.4.0

func (p *Sink) Publish(ctx context.Context, data []types.MetricDatum) error

Publish sends one batch of metric data to CloudWatch. The batch must not exceed maxMetricsPerRequest items.

func (*Sink) Run

func (p *Sink) Run(ctx context.Context)

Run starts a loop that will push metrics to Cloudwatch at the configured interval. Accepts a context.Context to support cancellation.

It returns when ctx is cancelled, after a final flush, or when publishing fails with expired or missing credentials, which cannot succeed on a retry.

func (*Sink) SetGauge

func (p *Sink) SetGauge(key string, val float64, tags []metrics.Tag)

SetGauge retains the last value it is set to, until it is published.

Jump to

Keyboard shortcuts

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