Extending instrumentations with the API

Use the OpenTelemetry API in combination with the Java agent to extend the automatically generated telemetry with custom spans and metrics

Introduction

In addition to the out-of-the-box instrumentation, you can extend the Java agent with custom manual instrumentation using the OpenTelemetry API. This allows you to create spans and metrics for your own code without doing too many code changes.

Dependencies

Add a dependency on the opentelemetry-api library.

Maven

<dependencies>
  <dependency>
    <groupId>io.opentelemetry</groupId>
    <artifactId>opentelemetry-api</artifactId>
    <version>1.46.0</version>
  </dependency>
</dependencies>

Gradle

dependencies {
    implementation('io.opentelemetry:opentelemetry-api:1.46.0')
}

OpenTelemetry

The Java agent is a special case where GlobalOpenTelemetry is set by the agent. Simply call GlobalOpenTelemetry.get() to access the OpenTelemetry instance.

Span

import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.trace.Tracer;

Tracer tracer = GlobalOpenTelemetry.getTracer("application");

Use the Tracer to create a span as explained in the Span section.

A full example can be found in the example repository.

Meter

import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.metrics.Meter;

Meter meter = GlobalOpenTelemetry.getMeter("application");

Use the Meter to create a counter, gauge or histogram as explained in the Meter section.

A full example can be found in the example repository.