|
1 | 1 | package dev.suresh.plugins |
2 | 2 |
|
| 3 | +import BuildConfig |
| 4 | +import io.ktor.http.HttpMethod |
3 | 5 | import io.ktor.server.application.* |
4 | | -import io.opentelemetry.api.OpenTelemetry |
| 6 | +import io.ktor.server.request.httpMethod |
| 7 | +import io.opentelemetry.api.trace.SpanKind |
| 8 | +import io.opentelemetry.instrumentation.ktor.v3_0.* |
| 9 | +import io.opentelemetry.sdk.OpenTelemetrySdk |
5 | 10 | import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk |
6 | 11 | import io.opentelemetry.semconv.ServiceAttributes |
| 12 | +import kotlin.time.Clock |
7 | 13 |
|
8 | 14 | fun Application.configureOTel() { |
9 | | - // install(OTelExtnPlugin) { enabled = true } |
10 | | - // |
11 | | - // install(KtorServerTracing) { |
12 | | - // setOpenTelemetry(GlobalOpenTelemetry.get()) |
13 | | - // attributeExtractor { |
14 | | - // onStart { attributes.put("start-time", Clock.System.now().toEpochMilliseconds()) } |
15 | | - // onEnd { attributes.put("end-time", Clock.System.now().toEpochMilliseconds()) } |
16 | | - // } |
17 | | - // } |
18 | | -} |
| 15 | + install(KtorServerTelemetry) { |
| 16 | + setOpenTelemetry(getOpenTelemetry(BuildConfig.name)) |
19 | 17 |
|
20 | | -/** |
21 | | - * [Manual |
22 | | - * instrumentation](https://opentelemetry.io/docs/languages/java/instrumentation/#acquiring-a-tracer-in-java-agent) |
23 | | - */ |
24 | | -fun getOpenTelemetry(serviceName: String): OpenTelemetry { |
25 | | - return AutoConfiguredOpenTelemetrySdk.builder() |
26 | | - .addResourceCustomizer { oldResource, _ -> |
27 | | - oldResource |
28 | | - .toBuilder() |
29 | | - .putAll(oldResource.attributes) |
30 | | - .put(ServiceAttributes.SERVICE_NAME, serviceName) |
31 | | - .build() |
| 18 | + spanKindExtractor { |
| 19 | + if (httpMethod == HttpMethod.Post) { |
| 20 | + SpanKind.PRODUCER |
| 21 | + } else { |
| 22 | + SpanKind.CLIENT |
32 | 23 | } |
33 | | - .build() |
34 | | - .openTelemetrySdk |
| 24 | + } |
| 25 | + |
| 26 | + attributesExtractor { |
| 27 | + onStart { attributes.put("start-time", Clock.System.now().toEpochMilliseconds()) } |
| 28 | + onEnd { attributes.put("end-time", Clock.System.now().toEpochMilliseconds()) } |
| 29 | + } |
| 30 | + } |
| 31 | + // install(OTelExtnPlugin) { enabled = true } |
35 | 32 | } |
| 33 | + |
| 34 | +/** See [Configure the SDK](https://opentelemetry.io/docs/languages/java/configuration/) */ |
| 35 | +fun getOpenTelemetry(serviceName: String): OpenTelemetrySdk = |
| 36 | + AutoConfiguredOpenTelemetrySdk.builder() |
| 37 | + .addResourceCustomizer { res, _ -> |
| 38 | + res.toBuilder() |
| 39 | + .putAll(res.attributes) |
| 40 | + .put(ServiceAttributes.SERVICE_NAME, serviceName) |
| 41 | + .build() |
| 42 | + } |
| 43 | + .build() |
| 44 | + .openTelemetrySdk |
0 commit comments