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 ΒΆ