Observability
Manual instrumentation
Add your own spans and metrics.
Kest already traces every HTTP request and counts it. Manual instrumentation is adding the parts only you know about: how long did the price calculation take, how many items were in the cart.
Spans
A span is a named, timed step inside a trace. Wrap the step:
@Injectable
class PricingService(private val tracing: Tracing, private val rules: RuleEngine) {
fun price(cart: Cart): Money = tracing.span("pricing.calculate") { // child of the current request's span
val base = tracing.span("pricing.base") { rules.basePrice(cart) }
val discounts = tracing.span("pricing.discounts") { rules.discounts(cart) }
base - discounts
}
}An exception thrown inside marks the span as failed (with the exception recorded) and is rethrown, so error handling does not change. In the trace viewer the spans nest under GET /cart/price and you see which part took the time.
Add detail to the current span with the OpenTelemetry API, for example the number of items:
io.opentelemetry.api.trace.Span.current().setAttribute("cart.items", cart.items.size.toLong())Or wrap a whole method with an annotation (the class and the method must be open, see method decorators):
@Traced("price-lookup") open fun lookup(sku: String): Price = ...Put the trace id in a log line so the two can be linked: log.info("slow quote (trace ${tracing.currentTraceId()})").
Metrics
@Injectable
class Orders(private val metrics: MetricsRegistry) {
private val placed = metrics.counter("orders_placed_total", "Orders placed", "channel")
private val value = metrics.histogram("order_value_dollars", "Order value", doubleArrayOf(10.0, 50.0, 100.0, 500.0))
init { metrics.gauge("orders_open", "Open orders") { openOrders().toDouble() } } // read at each scrape
fun place(o: Order) { placed.inc("web"); value.observe(o.total) }
}counter, gauge (set, inc, dec), histogram (observe, time { }), a callback gauge, and collector for a family computed at scrape time. Asking for the same name twice returns the same metric; a name used for a different kind is an error, and so is a wrong number of label values. See Metrics for what the three kinds mean and how to name and label them.
On methods
@Injectable
open class Checkout {
@Timed("checkout_seconds") @Counted("checkout_calls_total") open fun pay(order: Order) { ... }
}@Timed observes the duration into a histogram with the labels class, method, outcome (ok or error); @Counted counts calls with the same labels. Both need an open class and method.
Which one do I use?
| I want to know... | Use |
|---|---|
| how many times, per minute | a counter |
| how long it takes, as percentiles | a histogram (or @Timed) |
| a current level (queue length) | a gauge |
| why this one request was slow | a span |