|
| 1 | +# Library Instrumentation for Java HTTP Server |
| 2 | + |
| 3 | +Provides OpenTelemetry instrumentation for [Java HTTP Server](https://docs.oracle.com/en/java/javase/21/docs/api/jdk.httpserver/module-summary.html). |
| 4 | + |
| 5 | +## Quickstart |
| 6 | + |
| 7 | +### Add these dependencies to your project |
| 8 | + |
| 9 | +Replace `OPENTELEMETRY_VERSION` with the [latest |
| 10 | +release](https://search.maven.org/search?q=g:io.opentelemetry.instrumentation%20AND%20a:opentelemetry-java-http-server). |
| 11 | + |
| 12 | +For Maven, add to your `pom.xml` dependencies: |
| 13 | + |
| 14 | +```xml |
| 15 | +<dependencies> |
| 16 | + <dependency> |
| 17 | + <groupId>io.opentelemetry.instrumentation</groupId> |
| 18 | + <artifactId>opentelemetry-java-http-server</artifactId> |
| 19 | + <version>OPENTELEMETRY_VERSION</version> |
| 20 | + </dependency> |
| 21 | +</dependencies> |
| 22 | +``` |
| 23 | + |
| 24 | +For Gradle, add to your dependencies: |
| 25 | + |
| 26 | +```groovy |
| 27 | +implementation("io.opentelemetry.instrumentation:opentelemetry-java-http-server:OPENTELEMETRY_VERSION") |
| 28 | +``` |
| 29 | + |
| 30 | +### Usage |
| 31 | + |
| 32 | +The instrumentation library contains a `Filter` wrapper that provides OpenTelemetry-based spans |
| 33 | +and context propagation. |
| 34 | + |
| 35 | +```java |
| 36 | + |
| 37 | +import java.io.IOException; |
| 38 | +import java.net.InetSocketAddress; |
| 39 | + |
| 40 | +import com.sun.net.httpserver.HttpContext; |
| 41 | +import com.sun.net.httpserver.HttpServer; |
| 42 | + |
| 43 | +import io.opentelemetry.api.OpenTelemetry; |
| 44 | +import io.opentelemetry.sdk.OpenTelemetrySdk; |
| 45 | + |
| 46 | +public class Application { |
| 47 | + |
| 48 | + static void main(String args) throws IOException { |
| 49 | + |
| 50 | + final HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0); |
| 51 | + final HttpContext context = |
| 52 | + server.createContext( |
| 53 | + "/", |
| 54 | + ctx -> { |
| 55 | + // http logic |
| 56 | + }); |
| 57 | + |
| 58 | + OpenTelemetry otel = //... |
| 59 | + |
| 60 | + context.getFilters().add(JavaServerTelemetry.create(otel).otelFilter()); |
| 61 | + } |
| 62 | +} |
| 63 | +``` |
0 commit comments