Documentation
¶
Overview ¶
Package instrument provides RED and USE instrument sets on an OpenTelemetry go.opentelemetry.io/otel/metric.Meter, the push-side counterpart of the domain helpers in gitlab.com/phpboyscout/go/transport-metrics. It depends on the OpenTelemetry APIs only, so a library can call it without linking the SDK or an exporter.
Index ¶
- Variables
- func ObserveResult[T any](ctx context.Context, o *Operations, name string, fn func() (T, error)) (T, error)
- type BreakerState
- type Cache
- type CircuitBreaker
- func (cb *CircuitBreaker) Close() error
- func (cb *CircuitBreaker) Failure(ctx context.Context)
- func (cb *CircuitBreaker) SetState(state BreakerState)
- func (cb *CircuitBreaker) ShortCircuit(ctx context.Context)
- func (cb *CircuitBreaker) Success(ctx context.Context)
- func (cb *CircuitBreaker) Trip(ctx context.Context)
- type DB
- type HelperOption
- type Operations
- type PoolStats
- type Queue
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrNilMeter = errors.New("instrument: nil meter")
ErrNilMeter is returned by a helper's constructor when it is given no meter.
var ErrPoolRegistered = errors.New("instrument: pool already registered")
ErrPoolRegistered is returned when DB.RegisterPool is called more than once on a DB. A second callback would be summed with the first, not replace it.
Functions ¶
func ObserveResult ¶
func ObserveResult[T any](ctx context.Context, o *Operations, name string, fn func() (T, error)) (T, error)
ObserveResult is Operations.Observe for an operation that returns a value.
Example ¶
package main
import (
"context"
"fmt"
"go.opentelemetry.io/otel"
"gitlab.com/phpboyscout/go/observability/instrument"
)
func main() {
ops, err := instrument.NewOperations(otel.Meter("checkout"))
if err != nil {
fmt.Println(err)
return
}
total, err := instrument.ObserveResult(context.Background(), ops, "count_orders", func() (int, error) {
return 42, nil
})
fmt.Println(total, err)
}
Output: 42 <nil>
Types ¶
type BreakerState ¶
type BreakerState int
BreakerState is a circuit-breaker state, reported as its numeric value on circuit_breaker.state. The values are part of the metric's contract.
const ( // BreakerClosed means requests flow normally. BreakerClosed BreakerState = 0 // BreakerOpen means requests are short-circuited. BreakerOpen BreakerState = 1 // BreakerHalfOpen means a trial request is allowed, to test recovery. BreakerHalfOpen BreakerState = 2 )
func FromResilienceState ¶
func FromResilienceState(state int) BreakerState
FromResilienceState maps a go/transit resilience breaker state, passed as its numeric value, to a BreakerState. Unknown values read as BreakerClosed.
type Cache ¶
type Cache struct {
// contains filtered or unexported fields
}
Cache instruments a cache: hits, misses and evictions, plus its size and capacity. Create one with NewCache.
Example ¶
package main
import (
"context"
"fmt"
"go.opentelemetry.io/otel"
"gitlab.com/phpboyscout/go/observability/instrument"
)
func main() {
cache, err := instrument.NewCache(otel.Meter("checkout"), "sessions")
if err != nil {
fmt.Println(err)
return
}
ctx := context.Background()
cache.Hit(ctx)
cache.Miss(ctx)
cache.SetCapacity(1024)
cache.SetSize(1)
fmt.Println(cache.Close())
}
Output: <nil>
func NewCache ¶
NewCache creates the instruments on meter for the cache called name. Call Cache.Close when the cache goes away.
The name becomes an attribute value, so it must come from a small fixed set, never from a per-call value.
OpenTelemetry keeps one value per attribute set, so two caches sharing a name on one meter would overwrite each other's size. Names must be unique per meter.
func (*Cache) Close ¶
Close stops reporting the cache's size and capacity, and releases the callback that holds this Cache alive. It is safe to call more than once.
func (*Cache) Eviction ¶
Eviction records n evicted entries. A counter cannot go down, so an n below 1 is ignored.
func (*Cache) Miss ¶
Miss records a cache miss. A span in ctx attaches to the sample as an exemplar.
func (*Cache) SetCapacity ¶
SetCapacity sets the most entries the cache can hold, where 0 means unbounded.
type CircuitBreaker ¶
type CircuitBreaker struct {
// contains filtered or unexported fields
}
CircuitBreaker instruments a circuit breaker: its state, plus trips, short-circuits, successes and failures. Create one with NewCircuitBreaker.
Example ¶
package main
import (
"context"
"fmt"
"go.opentelemetry.io/otel"
"gitlab.com/phpboyscout/go/observability/instrument"
)
func main() {
breaker, err := instrument.NewCircuitBreaker(otel.Meter("checkout"), "payments")
if err != nil {
fmt.Println(err)
return
}
ctx := context.Background()
breaker.Failure(ctx)
breaker.Trip(ctx)
breaker.ShortCircuit(ctx)
breaker.SetState(instrument.BreakerHalfOpen)
breaker.Success(ctx)
breaker.SetState(instrument.BreakerClosed)
fmt.Println(breaker.Close())
}
Output: <nil>
func NewCircuitBreaker ¶
func NewCircuitBreaker(meter metric.Meter, name string, opts ...HelperOption) (*CircuitBreaker, error)
NewCircuitBreaker creates the instruments on meter for the breaker called name, in BreakerClosed. Call CircuitBreaker.Close when the breaker goes away.
The name becomes an attribute value, so it must come from a small fixed set, never from a per-call value.
OpenTelemetry keeps one value per attribute set, so two breakers sharing a name on one meter would overwrite each other's state. Names must be unique per meter.
func (*CircuitBreaker) Close ¶
func (cb *CircuitBreaker) Close() error
Close stops reporting the breaker's state, and releases the callback that holds this CircuitBreaker alive. It is safe to call more than once.
func (*CircuitBreaker) Failure ¶
func (cb *CircuitBreaker) Failure(ctx context.Context)
Failure records a failed request.
func (*CircuitBreaker) SetState ¶
func (cb *CircuitBreaker) SetState(state BreakerState)
SetState sets the breaker's state.
func (*CircuitBreaker) ShortCircuit ¶
func (cb *CircuitBreaker) ShortCircuit(ctx context.Context)
ShortCircuit records a request rejected while open.
func (*CircuitBreaker) Success ¶
func (cb *CircuitBreaker) Success(ctx context.Context)
Success records a successful request.
func (*CircuitBreaker) Trip ¶
func (cb *CircuitBreaker) Trip(ctx context.Context)
Trip records a transition to open, and sets the state to BreakerOpen. A span in ctx attaches to the sample as an exemplar.
type DB ¶
type DB struct {
// contains filtered or unexported fields
}
DB instruments a database: query RED under semantic-convention names and, once DB.RegisterPool is called, pool USE. Create one with NewDB.
func NewDB ¶
NewDB creates the query instruments on meter for the database called name.
Every query name passed to DB.Query becomes an attribute value, so names must be bounded, such as "get_user", never a raw SQL string with interpolated values.
func (*DB) Close ¶
Close unregisters the pool callback, after which the pool's metrics stop being reported. It is safe to call more than once, and on a DB with no pool.
func (*DB) Query ¶
Query runs fn as the named query and records its duration, its error type if it fails, and that it is in flight while it runs. fn's error is returned unchanged. A span in ctx attaches to the sample as an exemplar.
Example ¶
package main
import (
"context"
"fmt"
"go.opentelemetry.io/otel"
"gitlab.com/phpboyscout/go/observability/instrument"
)
func main() {
db, err := instrument.NewDB(otel.Meter("checkout"), "orders", instrument.WithDBSystem("postgresql"))
if err != nil {
fmt.Println(err)
return
}
defer func() {
if err := db.Close(); err != nil {
fmt.Println(err)
}
}()
err = db.Query(context.Background(), "get_order", func() error {
return nil
})
fmt.Println(err)
}
Output: <nil>
func (*DB) RegisterPool ¶
RegisterPool adds pool USE metrics sourced from fn, which runs on every collect, so keep it cheap, such as a mapping of sql.DB.Stats(). It may be called once per DB. Call DB.Close when the pool goes away, or the callback keeps fn, and whatever fn holds, alive for the life of the provider.
The database's name labels the pool, and OpenTelemetry sums callbacks that share their attributes, so pool names must be unique per meter.
type HelperOption ¶
type HelperOption func(*helperConfig)
HelperOption configures a helper.
func WithAttributes ¶
func WithAttributes(attrs ...attribute.KeyValue) HelperOption
WithAttributes adds constant attributes to everything the helper records. Each value must come from a small fixed set, as with an operation name.
func WithBuckets ¶
func WithBuckets(boundaries ...float64) HelperOption
WithBuckets overrides the duration histograms' bucket boundaries, in seconds.
func WithDBSystem ¶
func WithDBSystem(name string) HelperOption
WithDBSystem sets NewDB's db.system.name, which semantic conventions require, using their value for the database such as "postgresql". The default is their fallback, "other_sql". Other helpers ignore it.
type Operations ¶
type Operations struct {
// contains filtered or unexported fields
}
Operations is a RED instrument set for arbitrary operations, the generic way to instrument business logic. Rate and errors come from the duration histogram's count, filtered on error.type. Create one with NewOperations.
func NewOperations ¶
func NewOperations(meter metric.Meter, opts ...HelperOption) (*Operations, error)
NewOperations creates operation.duration and operation.active on meter.
Every operation name passed to Operations.Observe becomes an attribute value, so names must come from a small fixed set, never from a per-call value.
func (*Operations) Observe ¶
Observe runs fn as the named operation and records its duration, its error type if it fails, and that it is in flight while it runs. fn's error is returned unchanged. A span in ctx attaches to the sample as an exemplar.
Example ¶
package main
import (
"context"
"fmt"
"go.opentelemetry.io/otel"
"gitlab.com/phpboyscout/go/observability/instrument"
)
func main() {
ops, err := instrument.NewOperations(otel.Meter("checkout"))
if err != nil {
fmt.Println(err)
return
}
err = ops.Observe(context.Background(), "reindex", func() error {
return nil
})
fmt.Println(err)
}
Output: <nil>
type PoolStats ¶
type PoolStats struct {
MaxOpen int // configured max open connections (0 = unlimited)
Open int // connections currently open
InUse int // connections currently in use
Idle int // idle connections
WaitCount int64 // total connection waits
WaitSeconds float64 // cumulative time spent waiting for a connection
}
PoolStats is a snapshot of a connection pool, mapped by the caller from its driver's stats, such as database/sql's sql.DBStats. It feeds DB.RegisterPool.
type Queue ¶
type Queue struct {
// contains filtered or unexported fields
}
Queue instruments a queue: its depth, items in and out, and how long they wait and take to process. Create one with NewQueue.
Example ¶
package main
import (
"context"
"fmt"
"time"
"go.opentelemetry.io/otel"
"gitlab.com/phpboyscout/go/observability/instrument"
)
func main() {
queue, err := instrument.NewQueue(otel.Meter("checkout"), "emails")
if err != nil {
fmt.Println(err)
return
}
ctx := context.Background()
queue.Enqueue(ctx)
queue.SetDepth(1)
queue.Dequeue(ctx)
queue.SetDepth(0)
queue.ObserveWait(ctx, 2*time.Second)
queue.ObserveProcessing(ctx, 150*time.Millisecond)
fmt.Println("recorded")
}
Output: recorded
func NewQueue ¶
NewQueue creates the instruments on meter for the queue called name.
The name becomes an attribute value, so it must come from a small fixed set, never from a per-call value. Two queues sharing a name on one meter add together, depths included, so names must be unique per meter.
A Queue registers no callback, so it has nothing to close, and its depth keeps reporting the last value for the life of the provider: call SetDepth(0) when dropping a queue.
func (*Queue) Enqueue ¶
Enqueue records an item added to the queue. A span in ctx attaches to the sample as an exemplar.
func (*Queue) ObserveProcessing ¶
ObserveProcessing records how long an item took to process.
func (*Queue) ObserveWait ¶
ObserveWait records how long an item waited in the queue.