|
| 1 | +--- |
| 2 | +title: Extending instrumentations with the API |
| 3 | +linkTitle: Extend with the API |
| 4 | +description: |
| 5 | + Use the OpenTelemetry API in combination with the Spring Boot starter to |
| 6 | + extend the automatically generated telemetry with custom spans and metrics |
| 7 | +weight: 21 |
| 8 | +--- |
| 9 | + |
| 10 | +## Introduction |
| 11 | + |
| 12 | +In addition to the out-of-the-box instrumentation, you can extend the Spring |
| 13 | +starter with custom manual instrumentation using the OpenTelemetry API. This |
| 14 | +allows you to create [spans](/docs/concepts/signals/traces/#spans) and |
| 15 | +[metrics](/docs/concepts/signals/metrics) for your own code without doing too |
| 16 | +many code changes. |
| 17 | + |
| 18 | +The required dependencies are already included in the Spring Boot starter. |
| 19 | + |
| 20 | +## OpenTelemetry |
| 21 | + |
| 22 | +The Spring Boot starter is a special case where `OpenTelemetry` is available as |
| 23 | +a Spring bean. Simply inject `OpenTelemetry` into your Spring components. |
| 24 | + |
| 25 | +## Span |
| 26 | + |
| 27 | +{{% alert title="Note" color="info" %}} |
| 28 | + |
| 29 | +For the most common use cases, use the `@WithSpan` annotation instead of manual |
| 30 | +instrumentation. See [Annotations](../annotations) for more information. |
| 31 | + |
| 32 | +{{% /alert %}} |
| 33 | + |
| 34 | +```java |
| 35 | +import io.opentelemetry.api.OpenTelemetry; |
| 36 | +import io.opentelemetry.api.trace.Tracer; |
| 37 | + |
| 38 | +@Controller |
| 39 | +public class MyController { |
| 40 | + private final Tracer tracer; |
| 41 | + |
| 42 | + public MyController(OpenTelemetry openTelemetry) { |
| 43 | + this.tracer = openTelemetry.getTracer("application"); |
| 44 | + } |
| 45 | +} |
| 46 | +``` |
| 47 | + |
| 48 | +Use the `Tracer` to create a span as explained in the |
| 49 | +[Span](/docs/languages/java/api/#span) section. |
| 50 | + |
| 51 | +A full example can be found in the [example repository]. |
| 52 | + |
| 53 | +## Meter |
| 54 | + |
| 55 | +```java |
| 56 | +import io.opentelemetry.api.OpenTelemetry; |
| 57 | +import io.opentelemetry.api.metrics.Meter; |
| 58 | + |
| 59 | +@Controller |
| 60 | +public class MyController { |
| 61 | + private final Meter meter; |
| 62 | + |
| 63 | + public MyController(OpenTelemetry openTelemetry) { |
| 64 | + this.meter = openTelemetry.getMeter("application"); |
| 65 | + } |
| 66 | +} |
| 67 | +``` |
| 68 | + |
| 69 | +Use the `Meter` to create a counter, gauge or histogram as explained in the |
| 70 | +[Meter](/docs/languages/java/api/#meter) section. |
| 71 | + |
| 72 | +A full example can be found in the [example repository]. |
| 73 | + |
| 74 | +[example repository]: |
| 75 | + https://github.com/open-telemetry/opentelemetry-java-examples/tree/main/spring-native |
0 commit comments