Skip to content

Instrument an operation

Wrap the work in Operations.Observe. It records the duration, marks a failure with error.type, and counts the operation as in flight while it runs:

ops, err := instrument.NewOperations(mp.Meter("checkout"))
if err != nil {
    return err
}

err = ops.Observe(ctx, "reindex", func() error {
    return svc.Reindex(ctx)
})

Observe returns the function's error unchanged. It only observes.

Return a value

Go methods cannot take type parameters, so the value-returning form is a function:

total, err := instrument.ObserveResult(ctx, ops, "count_orders", func() (int, error) {
    return svc.CountOrders(ctx)
})

Keep operation names to a fixed set

The name becomes the value of the operation.name attribute, and every distinct value is a new series. Use "get_user", never "get_user_" + id. Nothing in the helper checks this. RED, USE and cardinality says what happens if you get it wrong.

Classify failures

A failed operation's error.type is the error's go/errors kind, or _OTHER if it has none. To make a failure queryable by cause, return an error with a kind:

var ErrBackendDown = errors.NewSentinel("backend_down", "the backend is down")

The error message never becomes an attribute.

Read the signals

Signal Query the histogram operation.duration for
Rate its count
Errors its count where error.type is present
Duration its buckets

operation.active holds the number running now. Run Observe inside a sampled span and the duration sample carries the trace as an exemplar, with nothing else to wire up.