metrics

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2026 License: MIT Imports: 18 Imported by: 1

Documentation

Overview

Package metrics emits CloudWatch Embedded Metric Format documents for AWS Lambda.

New configures namespace, service, dimensions and an io.Writer, which defaults to standard output. Metrics.AddMetric records values with a Unit and Resolution; Metrics.Flush publishes the accumulated EMF document. CloudWatch ingests EMF from Lambda logs, so publishing does not call its SDK.

Invocation lifecycle

WrapHandler manages metric publication around a typed handler. Use Metrics.WithContext inside that handler for isolated invocation state. Cold-start capture, empty-metric policy and error callbacks are configurable. Keep dimensions bounded: values such as request IDs create expensive cardinality.

Metrics uses io.Writer rather than depending on Logger or Tracer. Applications own custom writers and configuration callbacks.

For usage and compatibility details, see the user guide.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrInvocationClosed = errors.New("metrics invocation is closed")
	ErrEmptyMetrics     = errors.New("The number of metrics recorded must be higher than zero")
	ErrDimensionLimit   = errors.New("The number of metric dimensions must be lower than 29")
)

Functions

func WrapHandler

func WrapHandler[T, R any](m *Metrics, handler func(context.Context, T) (R, error), options ...HandlerOptions) func(context.Context, T) (R, error)

WrapHandler flushes on success, error, and panic and rejects late request writes. Flush errors go to WithErrorHandler. Business outcomes are preserved unless HandlerOptions.PropagateErrors selects reference publication-error precedence. Use WithContext inside the handler. Root-level pending metrics are not copied into requests.

func WrapHandlers

func WrapHandlers[T, R any](targets []*Metrics, handler func(context.Context, T) (R, error), options ...HandlerOptions) func(context.Context, T) (R, error)

WrapHandlers applies the reference middleware's ordered multi-instance lifecycle. It snapshots the target list and options, isolates request storage, and stops publication at the first error while closing every scope that it owns. Duplicate targets share storage and retain their repeated setup/publication calls. Existing outer scopes remain owned by their original wrapper.

Types

type ConfigService

type ConfigService interface {
	GetNamespace() (string, error)
	GetServiceName() (string, error)
}

ConfigService supplies the two custom settings used by the reference constructor. Getters run only when the corresponding explicit option is empty. Errors propagate unchanged. The reference declares a function-name getter but does not call it.

type Dimensions

type Dimensions map[string]string

type HandlerOptions

type HandlerOptions struct {
	CaptureColdStart bool
	// ThrowOnEmptyMetrics enables the scoped policy. False does not disable an inherited policy.
	ThrowOnEmptyMetrics bool
	// DefaultDimensions merges invocation defaults before cold-start capture.
	DefaultDimensions Dimensions
	// PropagateErrors lets publication errors replace the handler result, error or panic,
	// matching the reference finally/after behavior. The default preserves business outcomes.
	PropagateErrors bool
}

type Metrics

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

Metrics may be shared across handlers. Use WithContext inside WrapHandler for isolated request state. Configuration callbacks and custom writers are caller-owned.

func New

func New(options ...Option) (*Metrics, error)

func (*Metrics) AddDimension

func (m *Metrics) AddDimension(name, value string) error

func (*Metrics) AddDimensionSet

func (m *Metrics) AddDimensionSet(dimensions Dimensions) error

AddDimensionSet creates a separate dimension combination, matching TS addDimensions.

func (*Metrics) AddMetadata

func (m *Metrics) AddMetadata(key string, value any) error

AddMetadata snapshots JSON immediately so subsequent caller mutation cannot alter output.

func (*Metrics) AddMetric

func (m *Metrics) AddMetric(name string, unit Unit, value float64, resolutions ...Resolution) error

func (*Metrics) CaptureColdStartMetric

func (m *Metrics) CaptureColdStartMetric(functionName ...string) error

CaptureColdStartMetric emits one isolated ColdStart metric per Metrics instance for on-demand initialization. Bound scopes also require a cold invocation. The optional function name is used only when no configured name exists. The cold-start decision is consumed before writing, including failed writes.

func (*Metrics) Clear

func (m *Metrics) Clear() error

Clear removes request metrics, dimensions, metadata, and timestamp, retaining defaults.

func (*Metrics) ClearDefaultDimensions

func (m *Metrics) ClearDefaultDimensions() error

func (*Metrics) ClearDimensions

func (m *Metrics) ClearDimensions() error

ClearDimensions removes regular dimensions and independent dimension sets. Default dimensions, metrics, metadata and the timestamp are preserved.

func (*Metrics) ClearMetadata

func (m *Metrics) ClearMetadata() error

ClearMetadata removes metadata without changing metrics or dimensions.

func (*Metrics) ClearMetrics

func (m *Metrics) ClearMetrics() error

ClearMetrics removes buffered metrics and the explicit timestamp, retaining dimensions, metadata and the empty-metric policy, as in the reference store.

func (*Metrics) Disabled

func (m *Metrics) Disabled() bool

func (*Metrics) Flush

func (m *Metrics) Flush() error

Flush clears request state even if serialization or output fails, matching TS cleanup.

Example
package main

import (
	"bytes"
	"encoding/json"
	"fmt"

	"github.com/rambow-cloud/powertools-lambda-go/metrics"
)

func main() {
	var output bytes.Buffer
	m, err := metrics.New(metrics.WithNamespace("Example/Orders"),
		metrics.WithServiceName("orders"), metrics.WithOutput(&output), metrics.WithDisabled(false))
	if err != nil {
		panic(err)
	}
	if err := m.AddMetric("OrdersAccepted", metrics.Count, 1); err != nil {
		panic(err)
	}
	if err := m.Flush(); err != nil {
		panic(err)
	}
	var document map[string]any
	if err := json.Unmarshal(output.Bytes(), &document); err != nil {
		panic(err)
	}
	fmt.Println(document["OrdersAccepted"])
}
Output:
1

func (*Metrics) HasStoredMetrics

func (m *Metrics) HasStoredMetrics() bool

HasStoredMetrics reports whether the current scope has buffered metrics. Closing a scope flushes and clears it, so closed scopes report false.

func (*Metrics) Serialize

func (m *Metrics) Serialize() ([]byte, error)

Serialize snapshots an EMF document without flushing or clearing buffered metrics.

func (*Metrics) SetDefaultDimensions

func (m *Metrics) SetDefaultDimensions(dimensions Dimensions) error

SetDefaultDimensions merges defaults; invocation-bound defaults remain request-local.

func (*Metrics) SetFunctionName

func (m *Metrics) SetFunctionName(name string) error

SetFunctionName changes the active scope's cold-start function name. Empty values suppress the capture argument; clearing or flushing does not reset the name. Deprecated: use WithFunctionName or the CaptureColdStartMetric argument instead.

func (*Metrics) SetThrowOnEmptyMetrics

func (m *Metrics) SetThrowOnEmptyMetrics(enabled bool) error

SetThrowOnEmptyMetrics changes the current scope's empty-buffer policy. New request scopes inherit a snapshot. Clearing or flushing does not reset it.

func (*Metrics) SetTimestamp

func (m *Metrics) SetTimestamp(timestamp time.Time) error

SetTimestamp maps a Go instant to the reference Date input at millisecond precision. Values outside the JavaScript Date range warn and serialize as null.

func (*Metrics) SetTimestampMillis

func (m *Metrics) SetTimestampMillis(milliseconds float64) error

SetTimestampMillis maps the reference numeric timestamp input. Integer values are retained even outside CloudWatch's time window. Fractional/non-finite values warn and become zero, matching the reference numeric conversion rather than Date input.

func (*Metrics) SingleMetric

func (m *Metrics) SingleMetric() (*Metrics, error)

SingleMetric constructs independent state from current defaults and fresh environment settings. It shares the output, clock, warning callback and invocation closure. Each addition flushes. Constructor failures are returned before any metric is added.

func (*Metrics) StartScope

func (m *Metrics) StartScope(ctx context.Context) (context.Context, func() error)

StartScope creates independent metric storage and binds it to the returned context. It inherits the active scope's default dimensions, but not pending metrics or metadata. Call finish after all scoped work: it flushes once, rejects late writes, and returns the same flush error on repeated calls. The writer and configuration remain shared.

func (*Metrics) ThrowOnEmptyMetrics

func (m *Metrics) ThrowOnEmptyMetrics() error

ThrowOnEmptyMetrics enables the empty-buffer error policy. Deprecated: use SetThrowOnEmptyMetrics instead.

func (*Metrics) WithContext

func (m *Metrics) WithContext(ctx context.Context) *Metrics

type Option

type Option func(*config)

func WithClock

func WithClock(clock func() time.Time) Option

WithClock supplies a concurrency-safe clock for timestamps and validation.

func WithConfigService

func WithConfigService(service ConfigService) Option

WithConfigService supplies constructor fallbacks before environment settings. The service is called during construction, outside all metric storage locks.

func WithDefaultDimensions

func WithDefaultDimensions(dimensions Dimensions) Option

func WithDisabled

func WithDisabled(disabled bool) Option

func WithErrorHandler

func WithErrorHandler(handler func(error)) Option

WithErrorHandler observes wrapper flush failures without replacing business errors.

func WithFunctionName

func WithFunctionName(name string) Option

func WithNamespace

func WithNamespace(namespace string) Option

func WithOutput

func WithOutput(writer io.Writer) Option

func WithRequireMetrics

func WithRequireMetrics(required bool) Option

func WithServiceName

func WithServiceName(service string) Option

func WithSingleMetric

func WithSingleMetric(single bool) Option

WithSingleMetric enables immediate publication after each metric addition.

func WithWarningHandler

func WithWarningHandler(handler func(string)) Option

WithWarningHandler receives reference-compatible diagnostics. It may run during construction and concurrently across requests. Storage locks are released first. Pass a no-op function to suppress warnings; the default writes to stderr. Callbacks must handle their own synchronization and must not panic or recursively finish the scope that is delivering them. Callback panics propagate to the caller.

type Resolution

type Resolution int
const (
	Standard Resolution = 60
	High     Resolution = 1
)

type Unit

type Unit string
const (
	Seconds            Unit = "Seconds"
	Microseconds       Unit = "Microseconds"
	Milliseconds       Unit = "Milliseconds"
	Bytes              Unit = "Bytes"
	Kilobytes          Unit = "Kilobytes"
	Megabytes          Unit = "Megabytes"
	Gigabytes          Unit = "Gigabytes"
	Terabytes          Unit = "Terabytes"
	Bits               Unit = "Bits"
	Kilobits           Unit = "Kilobits"
	Megabits           Unit = "Megabits"
	Gigabits           Unit = "Gigabits"
	Terabits           Unit = "Terabits"
	Percent            Unit = "Percent"
	Count              Unit = "Count"
	BytesPerSecond     Unit = "Bytes/Second"
	KilobytesPerSecond Unit = "Kilobytes/Second"
	MegabytesPerSecond Unit = "Megabytes/Second"
	GigabytesPerSecond Unit = "Gigabytes/Second"
	TerabytesPerSecond Unit = "Terabytes/Second"
	BitsPerSecond      Unit = "Bits/Second"
	KilobitsPerSecond  Unit = "Kilobits/Second"
	MegabitsPerSecond  Unit = "Megabits/Second"
	GigabitsPerSecond  Unit = "Gigabits/Second"
	TerabitsPerSecond  Unit = "Terabits/Second"
	CountPerSecond     Unit = "Count/Second"
	NoUnit             Unit = "None"
)

Jump to

Keyboard shortcuts

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