diff --git a/src/ConsoleInstrumentation.php b/src/ConsoleInstrumentation.php index 05fa068..94362de 100644 --- a/src/ConsoleInstrumentation.php +++ b/src/ConsoleInstrumentation.php @@ -12,12 +12,27 @@ use OpenTelemetry\API\Trace\StatusCode; use OpenTelemetry\Context\Context; use function OpenTelemetry\Instrumentation\hook; +use OpenTelemetry\SDK\Common\Configuration\Configuration; use OpenTelemetry\SemConv\TraceAttributes; use Throwable; class ConsoleInstrumentation { public static function register(CachedInstrumentation $instrumentation): void + { + if (self::shouldTraceCli()) { + self::hookConsoleKernel($instrumentation); + } + + self::hookCommandExecution($instrumentation); + } + + private static function shouldTraceCli(): bool + { + return PHP_SAPI !== 'cli' || Configuration::getBoolean('OTEL_PHP_TRACE_CLI_ENABLED', false); + } + + private static function hookConsoleKernel(CachedInstrumentation $instrumentation): void { hook( Kernel::class, @@ -58,7 +73,10 @@ public static function register(CachedInstrumentation $instrumentation): void $span->end(); } ); + } + private static function hookCommandExecution(CachedInstrumentation $instrumentation): void + { hook( Command::class, 'execute', diff --git a/tests/Integration/ConsoleInstrumentationTest.php b/tests/Integration/ConsoleInstrumentationTest.php index 4abc6d5..16a7f98 100644 --- a/tests/Integration/ConsoleInstrumentationTest.php +++ b/tests/Integration/ConsoleInstrumentationTest.php @@ -27,14 +27,15 @@ public function test_command_tracing(): void * * @see \Illuminate\Foundation\Console\OptimizeClearCommand::handle() for the additional commands/spans. */ - $count = 8; - $this->assertCount($count, $this->storage); - - $span = $this->storage[--$count]; - $this->assertSame('Artisan handler', $span->getName()); - - $span = $this->storage[--$count]; - $this->assertSame('Command optimize:clear', $span->getName()); + $this->assertCount(7, $this->storage); + + $this->assertSame('Command event:clear', $this->storage[0]->getName()); + $this->assertSame('Command view:clear', $this->storage[1]->getName()); + $this->assertSame('Command cache:clear', $this->storage[2]->getName()); + $this->assertSame('Command route:clear', $this->storage[3]->getName()); + $this->assertSame('Command config:clear', $this->storage[4]->getName()); + $this->assertSame('Command clear-compiled', $this->storage[5]->getName()); + $this->assertSame('Command optimize:clear', $this->storage[6]->getName()); } private function kernel(): Kernel