|
| 1 | +/* |
| 2 | + * Copyright (C) Gustav Karlsson |
| 3 | + * |
| 4 | + * <p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file |
| 5 | + * except in compliance with the License. You may obtain a copy of the License at |
| 6 | + * |
| 7 | + * <p>http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | + * |
| 9 | + * <p>Unless required by applicable law or agreed to in writing, software distributed under the |
| 10 | + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either |
| 11 | + * express or implied. See the License for the specific language governing permissions and |
| 12 | + * limitations under the License. |
| 13 | + */ |
| 14 | +package com.github.kagkarlsson.scheduler.event; |
| 15 | + |
| 16 | +import com.github.kagkarlsson.scheduler.CurrentlyExecuting; |
| 17 | +import com.github.kagkarlsson.scheduler.task.ExecutionComplete; |
| 18 | +import com.github.kagkarlsson.scheduler.task.ExecutionComplete.Result; |
| 19 | +import com.github.kagkarlsson.scheduler.task.TaskInstance; |
| 20 | +import io.opentelemetry.api.OpenTelemetry; |
| 21 | +import io.opentelemetry.api.trace.Span; |
| 22 | +import io.opentelemetry.api.trace.Tracer; |
| 23 | + |
| 24 | +public class OtelTracingListener extends AbstractSchedulerListener { |
| 25 | + |
| 26 | + private final OpenTelemetry openTelemetry; |
| 27 | + |
| 28 | + public OtelTracingListener(OpenTelemetry openTelemetry) { |
| 29 | + this.openTelemetry = openTelemetry; |
| 30 | + } |
| 31 | + |
| 32 | + @Override |
| 33 | + public void onExecutionStart(CurrentlyExecuting currentlyExecuting) { |
| 34 | + Tracer t = openTelemetry.getTracer("db-scheduler.execution"); |
| 35 | + TaskInstance<?> taskInstance = currentlyExecuting.getTaskInstance(); |
| 36 | + Span span = |
| 37 | + t.spanBuilder("execute") |
| 38 | + .setAttribute("task-name", taskInstance.getTaskName()) |
| 39 | + .setAttribute("task-instance-id", taskInstance.getId()) |
| 40 | + .startSpan(); |
| 41 | + span.makeCurrent(); |
| 42 | + } |
| 43 | + |
| 44 | + @Override |
| 45 | + public void onExecutionComplete(ExecutionComplete executionComplete) { |
| 46 | + Span currentSpan = Span.current(); |
| 47 | + |
| 48 | + try { |
| 49 | + if (executionComplete.getResult() == Result.FAILED) { |
| 50 | + executionComplete.getCause().ifPresent(currentSpan::recordException); |
| 51 | + } |
| 52 | + } finally { |
| 53 | + currentSpan.end(); |
| 54 | + } |
| 55 | + } |
| 56 | +} |
0 commit comments