observability

package
v1.0.78 Latest Latest
Warning

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

Go to latest
Published: Dec 15, 2025 License: Apache-2.0 Imports: 13 Imported by: 0

Documentation

Overview

Package observability defines interfaces and common types for structured logging and metrics used across Lift. Concrete implementations (e.g., CloudWatch logging and metrics) live under subpackages and integrate with the Lift Context and middleware for consistent telemetry in Lambda.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func WithSNSNotifier added in v1.0.30

func WithSNSNotifier(notifier *SNSNotifier) interface{}

WithSNSNotifier creates an option with the specified SNS notifier

Types

type AlertConfig added in v1.0.30

type AlertConfig struct {
	AlertType       string `json:"alert_type"`
	AlertTargetType string `json:"alert_target_type"`
}

AlertConfig contains alert configuration

type CheckResult

type CheckResult struct {
	Message  string        `json:"message,omitempty"`
	Error    string        `json:"error,omitempty"`
	Duration time.Duration `json:"duration"`
	Healthy  bool          `json:"healthy"`
	Critical bool          `json:"critical"`
}

CheckResult represents the result of a single health check

type CloudWatchLogsClient

CloudWatchLogsClient defines the interface for CloudWatch Logs operations This interface allows for easy mocking and testing

type HealthChecker

type HealthChecker interface {
	Check(ctx context.Context) error
	Name() string
	IsCritical() bool
}

HealthChecker defines the interface for health checking

type HealthStatus

type HealthStatus struct {
	Timestamp time.Time              `json:"timestamp"`
	Checks    map[string]CheckResult `json:"checks"`
	Version   string                 `json:"version,omitempty"`
	Healthy   bool                   `json:"healthy"`
}

HealthStatus represents the overall health status

type LogBuffer

type LogBuffer interface {
	Add(entry *LogEntry) error
	Flush(ctx context.Context) error
	Size() int
	IsFull() bool
	Clear()
	Close() error
}

LogBuffer defines the interface for buffering log entries

type LogEntry

type LogEntry struct {
	Timestamp time.Time      `json:"timestamp"`
	Level     string         `json:"level"`
	Message   string         `json:"message"`
	Fields    map[string]any `json:"fields,omitempty"`
	RequestID string         `json:"request_id,omitempty"`
	TenantID  string         `json:"tenant_id,omitempty"`
	UserID    string         `json:"user_id,omitempty"`
	TraceID   string         `json:"trace_id,omitempty"`
	SpanID    string         `json:"span_id,omitempty"`
}

LogEntry represents a structured log entry with multi-tenant context

type LogSink

type LogSink interface {
	Send(ctx context.Context, entries []*LogEntry) error
	Close() error
}

LogSink defines the interface for sending logs to a destination

type LoggerConfig

type LoggerConfig struct {
	Format          string        `json:"format"`
	DefaultUserID   string        `json:"default_user_id"`
	Level           string        `json:"level"`
	LogGroup        string        `json:"log_group"`
	LogStream       string        `json:"log_stream"`
	DefaultTenantID string        `json:"default_tenant_id"`
	RetryDelay      time.Duration `json:"retry_delay"`
	BatchSize       int           `json:"batch_size"`
	FlushInterval   time.Duration `json:"flush_interval"`
	BufferSize      int           `json:"buffer_size"`
	MaxRetries      int           `json:"max_retries"`
	EnableStack     bool          `json:"enable_stack"`
	AsyncLogging    bool          `json:"async_logging"`
	EnableCaller    bool          `json:"enable_caller"`
}

LoggerConfig holds configuration for logger implementations

func NewDefaultLoggerConfig added in v1.0.29

func NewDefaultLoggerConfig(level string) LoggerConfig

NewDefaultLoggerConfig creates a LoggerConfig with sensible defaults for Lambda environments. It accepts a log level parameter and automatically configures CloudWatch log group and stream based on environment variables.

func NewLoggerConfigWithOptions added in v1.0.29

func NewLoggerConfigWithOptions(level string, opts ...LoggerConfigOption) LoggerConfig

NewLoggerConfigWithOptions creates a LoggerConfig with custom options while maintaining defaults. It accepts a log level and allows overriding specific configuration options.

type LoggerConfigOption added in v1.0.29

type LoggerConfigOption func(*LoggerConfig)

LoggerConfigOption is a functional option for customizing LoggerConfig

func WithAsyncLogging added in v1.0.29

func WithAsyncLogging() LoggerConfigOption

WithAsyncLogging enables async logging

func WithBatchSize added in v1.0.29

func WithBatchSize(size int) LoggerConfigOption

WithBatchSize sets a custom batch size

func WithBufferSize added in v1.0.29

func WithBufferSize(size int) LoggerConfigOption

WithBufferSize sets a custom buffer size

func WithCallerInfo added in v1.0.29

func WithCallerInfo() LoggerConfigOption

WithCallerInfo enables caller information in logs

func WithFlushInterval added in v1.0.29

func WithFlushInterval(interval time.Duration) LoggerConfigOption

WithFlushInterval sets a custom flush interval

func WithFormat added in v1.0.29

func WithFormat(format string) LoggerConfigOption

WithFormat sets the log format (json or console)

func WithLogGroup added in v1.0.29

func WithLogGroup(logGroup string) LoggerConfigOption

WithLogGroup sets a custom log group

func WithLogStream added in v1.0.29

func WithLogStream(logStream string) LoggerConfigOption

WithLogStream sets a custom log stream

func WithRetryConfig added in v1.0.29

func WithRetryConfig(maxRetries int, retryDelay time.Duration) LoggerConfigOption

WithRetryConfig sets retry configuration

func WithStackTrace added in v1.0.29

func WithStackTrace() LoggerConfigOption

WithStackTrace enables stack traces for errors

func WithTenantContext added in v1.0.29

func WithTenantContext(tenantID, userID string) LoggerConfigOption

WithTenantContext sets default tenant and user IDs

type LoggerFactory

type LoggerFactory interface {
	CreateConsoleLogger(config LoggerConfig) (StructuredLogger, error)
	CreateCloudWatchLogger(config LoggerConfig, client CloudWatchLogsClient) (StructuredLogger, error)
	CreateTestLogger() StructuredLogger
	CreateNoOpLogger() StructuredLogger
}

LoggerFactory creates logger instances with different configurations

type LoggerStats

type LoggerStats struct {
	LastFlush        time.Time     `json:"last_flush"`
	LastError        string        `json:"last_error,omitempty"`
	EntriesLogged    int64         `json:"entries_logged"`
	EntriesDropped   int64         `json:"entries_dropped"`
	FlushCount       int64         `json:"flush_count"`
	BufferSize       int           `json:"buffer_size"`
	BufferCapacity   int           `json:"buffer_capacity"`
	AverageFlushTime time.Duration `json:"average_flush_time"`
	ErrorCount       int64         `json:"error_count"`
}

LoggerStats provides metrics about logger performance

type MetricEntry

type MetricEntry struct {
	Timestamp time.Time         `json:"timestamp"`
	Tags      map[string]string `json:"tags,omitempty"`
	Fields    map[string]any    `json:"fields,omitempty"`
	Name      string            `json:"name"`
	Unit      string            `json:"unit"`
	Value     float64           `json:"value"`
}

MetricEntry represents a metric data point

type MetricsCollector

type MetricsCollector interface {
	// Explicitly declare lift.MetricsCollector methods to avoid interface embedding issues
	Counter(name string, tags ...map[string]string) lift.Counter
	Histogram(name string, tags ...map[string]string) lift.Histogram
	Gauge(name string, tags ...map[string]string) lift.Gauge
	Flush() error

	// Additional methods for enhanced functionality
	RecordLatency(operation string, duration time.Duration)
	RecordError(operation string)
	RecordSuccess(operation string)

	// Context methods
	WithTags(tags map[string]string) MetricsCollector
	WithTag(key, value string) MetricsCollector

	// Batch operations
	RecordBatch(entries []*MetricEntry) error

	// Performance methods
	Close() error
	GetStats() MetricsStats
}

MetricsCollector extends the basic lift.MetricsCollector with additional functionality

type MetricsStats

type MetricsStats struct {
	LastFlush       time.Time `json:"last_flush"`
	LastError       string    `json:"last_error,omitempty"`
	MetricsRecorded int64     `json:"metrics_recorded"`
	MetricsDropped  int64     `json:"metrics_dropped"`
	ErrorCount      int64     `json:"error_count"`
}

MetricsStats provides information about metrics collection

type ObservabilityProvider

type ObservabilityProvider interface {
	Logger() StructuredLogger
	Metrics() MetricsCollector
	HealthChecker() HealthChecker
	Close() error
}

ObservabilityProvider combines logging, metrics, and health checking

type SNSClient added in v1.0.30

type SNSClient interface {
	Publish(ctx context.Context, params *sns.PublishInput, optFns ...func(*sns.Options)) (*sns.PublishOutput, error)
}

SNSClient defines the interface for SNS operations This interface allows for easy mocking and testing

type SNSConfig added in v1.0.30

type SNSConfig struct {
	Client   SNSClient
	TopicARN string
}

SNSConfig contains configuration for SNS notifications

type SNSNotificationMessage added in v1.0.30

type SNSNotificationMessage struct {
	AlertConfig AlertConfig `json:"alert_config"`
	LogTime     string      `json:"log_time"`
	Environment string      `json:"environment,omitempty"`
	Service     string      `json:"service,omitempty"`
	Partner     string      `json:"partner"`
	Stage       string      `json:"stage"`
	AWSRegion   string      `json:"aws_region"`
	AWSAccount  string      `json:"aws_account"`
	Function    string      `json:"function"`
	Subsystem   string      `json:"subsystem"`
	Severity    string      `json:"severity"`
	Message     string      `json:"message"`
}

SNSNotificationMessage represents the structure sent to SNS

type SNSNotifier added in v1.0.30

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

SNSNotifier handles sending error notifications to AWS SNS

func NewSNSNotifier added in v1.0.30

func NewSNSNotifier(config SNSConfig) *SNSNotifier

NewSNSNotifier creates a new SNS notifier from configuration

func WithDefaultErrorNotifications added in v1.0.30

func WithDefaultErrorNotifications(snsClient SNSClient) *SNSNotifier

WithDefaultErrorNotifications creates an SNS notifier using the centralized cross-account topic pattern used by all Pay Theory services (matching Python services).

This publishes to the main Pay Theory account (805600764437) for centralized error monitoring across all Pay Theory services and partners. The topic ARN format is: arn:aws:sns:us-east-1:805600764437:global-logs-publisher-topic-{stage}

Supported stages: paytheory, paytheorylab, paytheorystudy Defaults to paytheory for unknown stages.

This is the recommended method for all Lift-based services.

func WithErrorNotifications added in v1.0.30

func WithErrorNotifications(snsClient SNSClient, topicARN string) *SNSNotifier

WithErrorNotifications creates an SNS notifier with the specified topic ARN

func WithPartnerErrorNotifications added in v1.0.64

func WithPartnerErrorNotifications(snsClient SNSClient) *SNSNotifier

WithPartnerErrorNotifications creates an SNS notifier with partner-specific configuration. It builds the SNS topic ARN using the partner-specific format: cns-{partner}-{stage}

The AWS account ID is auto-detected using multiple strategies: 1. AWS_ACCOUNT_ID environment variable (if explicitly set) 2. STS GetCallerIdentity API call (works in any AWS environment)

Returns nil if required environment variables are not set or account ID cannot be determined.

Use this only if you need a partner-specific SNS topic instead of the centralized cross-account topic. Most services should use WithDefaultErrorNotifications instead.

func (*SNSNotifier) GetTopicARN added in v1.0.30

func (n *SNSNotifier) GetTopicARN() string

GetTopicARN returns the configured SNS topic ARN

func (*SNSNotifier) NotifyError added in v1.0.30

func (n *SNSNotifier) NotifyError(ctx context.Context, logEntry *LogEntry) error

NotifyError sends an error notification to SNS when an error is logged

type StructuredLogger

type StructuredLogger interface {
	// Explicitly declare lift.Logger methods to avoid interface embedding issues
	Debug(message string, fields ...map[string]any)
	Info(message string, fields ...map[string]any)
	Warn(message string, fields ...map[string]any)
	Error(message string, fields ...map[string]any)
	WithField(key string, value any) lift.Logger
	WithFields(fields map[string]any) lift.Logger

	// Context methods for multi-tenant logging
	WithRequestID(requestID string) StructuredLogger
	WithTenantID(tenantID string) StructuredLogger
	WithUserID(userID string) StructuredLogger
	WithTraceID(traceID string) StructuredLogger
	WithSpanID(spanID string) StructuredLogger

	// Performance and health methods
	Flush(ctx context.Context) error
	Close() error
	IsHealthy() bool
	GetStats() LoggerStats
}

StructuredLogger extends the basic lift.Logger with additional context methods

type TestObservabilityProvider

type TestObservabilityProvider interface {
	ObservabilityProvider

	// Test-specific methods
	GetLogEntries() []*LogEntry
	GetMetricEntries() []*MetricEntry
	ClearLogs()
	ClearMetrics()
	SimulateError(component string, err error)
	GetCallCount(method string) int
}

TestObservabilityProvider provides test implementations

Directories

Path Synopsis
Package aws provides helper utilities and adapters for AWS SDK error inspection and metadata used by Lift observability components.
Package aws provides helper utilities and adapters for AWS SDK error inspection and metadata used by Lift observability components.
Package cloudwatch contains structured logger and metrics implementations backed by Amazon CloudWatch.
Package cloudwatch contains structured logger and metrics implementations backed by Amazon CloudWatch.
Package xray provides integration helpers for AWS X-Ray, including middleware and utility functions to add subsegments, annotations, and metadata to traces in serverless applications built with Lift.
Package xray provides integration helpers for AWS X-Ray, including middleware and utility functions to add subsegments, annotations, and metadata to traces in serverless applications built with Lift.

Jump to

Keyboard shortcuts

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