|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Overtrue\LaravelOpenTelemetry\Watchers; |
| 4 | + |
| 5 | +use Illuminate\Console\Events\ScheduledTaskFailed; |
| 6 | +use Illuminate\Console\Events\ScheduledTaskFinished; |
| 7 | +use Illuminate\Console\Events\ScheduledTaskStarting; |
| 8 | +use Illuminate\Contracts\Foundation\Application; |
| 9 | +use OpenTelemetry\API\Trace\SpanInterface; |
| 10 | +use OpenTelemetry\API\Trace\StatusCode; |
| 11 | +use OpenTelemetry\Context\Context; |
| 12 | +use Overtrue\LaravelOpenTelemetry\Facades\Measure; |
| 13 | + |
| 14 | +class ScheduledTaskWatcher implements Watcher |
| 15 | +{ |
| 16 | + protected SpanInterface $span; |
| 17 | + |
| 18 | + public function register(Application $app): void |
| 19 | + { |
| 20 | + $app['events']->listen(ScheduledTaskStarting::class, function (ScheduledTaskStarting $event) { |
| 21 | + $this->span = Measure::span('[Schedule] '.$event->task->getSummaryForDisplay()) |
| 22 | + ->setAttributes([ |
| 23 | + 'task.command' => $event->task->command, |
| 24 | + 'task.description' => $event->task->description, |
| 25 | + 'task.expression' => $event->task->expression, |
| 26 | + 'task.exitCode' => $event->task->exitCode, |
| 27 | + ]) |
| 28 | + ->start(); |
| 29 | + $this->span->storeInContext(Context::getCurrent()); |
| 30 | + }); |
| 31 | + |
| 32 | + $app['events']->listen(ScheduledTaskFinished::class, function (ScheduledTaskFinished $event) { |
| 33 | + $this->span->end(); |
| 34 | + }); |
| 35 | + |
| 36 | + $app['events']->listen(ScheduledTaskFailed::class, function (ScheduledTaskFailed $event) { |
| 37 | + $this->span->setAttribute('task.error', $event->exception->getMessage()); |
| 38 | + $this->span->setStatus(StatusCode::STATUS_ERROR); |
| 39 | + $this->span->recordException($event->exception); |
| 40 | + $this->span->end(); |
| 41 | + }); |
| 42 | + } |
| 43 | +} |
0 commit comments