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 ¶
- Variables
- func WrapHandler[T, R any](m *Metrics, handler func(context.Context, T) (R, error), ...) func(context.Context, T) (R, error)
- func WrapHandlers[T, R any](targets []*Metrics, handler func(context.Context, T) (R, error), ...) func(context.Context, T) (R, error)
- type ConfigService
- type Dimensions
- type HandlerOptions
- type Metrics
- func (m *Metrics) AddDimension(name, value string) error
- func (m *Metrics) AddDimensionSet(dimensions Dimensions) error
- func (m *Metrics) AddMetadata(key string, value any) error
- func (m *Metrics) AddMetric(name string, unit Unit, value float64, resolutions ...Resolution) error
- func (m *Metrics) CaptureColdStartMetric(functionName ...string) error
- func (m *Metrics) Clear() error
- func (m *Metrics) ClearDefaultDimensions() error
- func (m *Metrics) ClearDimensions() error
- func (m *Metrics) ClearMetadata() error
- func (m *Metrics) ClearMetrics() error
- func (m *Metrics) Disabled() bool
- func (m *Metrics) Flush() error
- func (m *Metrics) HasStoredMetrics() bool
- func (m *Metrics) Serialize() ([]byte, error)
- func (m *Metrics) SetDefaultDimensions(dimensions Dimensions) error
- func (m *Metrics) SetFunctionName(name string) error
- func (m *Metrics) SetThrowOnEmptyMetrics(enabled bool) error
- func (m *Metrics) SetTimestamp(timestamp time.Time) error
- func (m *Metrics) SetTimestampMillis(milliseconds float64) error
- func (m *Metrics) SingleMetric() (*Metrics, error)
- func (m *Metrics) StartScope(ctx context.Context) (context.Context, func() error)
- func (m *Metrics) ThrowOnEmptyMetrics() error
- func (m *Metrics) WithContext(ctx context.Context) *Metrics
- type Option
- func WithClock(clock func() time.Time) Option
- func WithConfigService(service ConfigService) Option
- func WithDefaultDimensions(dimensions Dimensions) Option
- func WithDisabled(disabled bool) Option
- func WithErrorHandler(handler func(error)) Option
- func WithFunctionName(name string) Option
- func WithNamespace(namespace string) Option
- func WithOutput(writer io.Writer) Option
- func WithRequireMetrics(required bool) Option
- func WithServiceName(service string) Option
- func WithSingleMetric(single bool) Option
- func WithWarningHandler(handler func(string)) Option
- type Resolution
- type Unit
Examples ¶
Constants ¶
This section is empty.
Variables ¶
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 ¶
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 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 (*Metrics) AddDimension ¶
func (*Metrics) AddDimensionSet ¶
func (m *Metrics) AddDimensionSet(dimensions Dimensions) error
AddDimensionSet creates a separate dimension combination, matching TS addDimensions.
func (*Metrics) AddMetadata ¶
AddMetadata snapshots JSON immediately so subsequent caller mutation cannot alter output.
func (*Metrics) CaptureColdStartMetric ¶
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 ¶
Clear removes request metrics, dimensions, metadata, and timestamp, retaining defaults.
func (*Metrics) ClearDefaultDimensions ¶
func (*Metrics) ClearDimensions ¶
ClearDimensions removes regular dimensions and independent dimension sets. Default dimensions, metrics, metadata and the timestamp are preserved.
func (*Metrics) ClearMetadata ¶
ClearMetadata removes metadata without changing metrics or dimensions.
func (*Metrics) ClearMetrics ¶
ClearMetrics removes buffered metrics and the explicit timestamp, retaining dimensions, metadata and the empty-metric policy, as in the reference store.
func (*Metrics) Flush ¶
Flush clears request state even if serialization or output fails, matching TS cleanup.
Example ¶
package main
import (
"bytes"
json "encoding/json/v2"
"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 ¶
HasStoredMetrics reports whether the current scope has buffered metrics. Closing a scope flushes and clears it, so closed scopes report false.
func (*Metrics) Serialize ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
ThrowOnEmptyMetrics enables the empty-buffer error policy. Deprecated: use SetThrowOnEmptyMetrics instead.
type Option ¶
type Option func(*config)
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 WithErrorHandler ¶
WithErrorHandler observes wrapper flush failures without replacing business errors.
func WithFunctionName ¶
func WithNamespace ¶
func WithOutput ¶
func WithRequireMetrics ¶
func WithServiceName ¶
func WithSingleMetric ¶
WithSingleMetric enables immediate publication after each metric addition.
func WithWarningHandler ¶
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 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" )