Extending instrumentations with the API
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
Note
For the most common use cases, use the@WithSpan
annotation instead of manual
instrumentation. See Annotations for more information.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.
Feedback
Was this page helpful?
Thank you. Your feedback is appreciated!
Please let us know how we can improve this page. Your feedback is appreciated!