Adding Custom Spans and Metrics ¶

Auto-instrumentation covers HTTP, database, and messaging calls out of the box. To trace your own business logic or track application-specific events, add custom spans and metrics using the OpenTelemetry SDK.

Prerequisites ¶

1. Add custom spans ¶

Custom spans let you trace operations not covered by auto-instrumentation — business logic, batch jobs, or complex workflows.

Kotlin with @WithSpan ¶

The @WithSpan annotation is the simplest way to trace a method. The OpenTelemetry Java agent picks it up automatically.

Add the dependency:

kotlin
xml

Then annotate methods you want to trace:

kotlin

Java with the Tracer API ¶

For more control (dynamic span names, adding events, setting status), use the Tracer API directly:

java

Node.js ¶

javascript

2. Add custom metrics ¶

Custom metrics track application-specific counters, gauges, or histograms. These are exported to Mimir and available in Grafana.

Kotlin / Java ¶

kotlin

OTel Metrics API

Use GlobalOpenTelemetry.getMeter() (not GlobalMeterProvider.getMeter(), which was removed in OpenTelemetry Java 2.x).

Node.js ¶

javascript

3. Verify in APM ¶

  1. Deploy your application
  2. Open the Nais APM and find your service
  3. Check the Operations tab — your custom spans appear as operations
  4. In Grafana Explore, query your custom metrics with PromQL

Next steps ¶