Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions src/API/Instrumentation/WithSpanHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

declare(strict_types=1);

namespace OpenTelemetry\API\Instrumentation;

use OpenTelemetry\API\Trace\Span;
use OpenTelemetry\API\Trace\SpanKind;
use OpenTelemetry\API\Trace\StatusCode;
use OpenTelemetry\Context\Context;
use Throwable;

/**
* Generic pre-hook and post-hook handlers for attribute-based auto instrumentation
*/
class WithSpanHandler
{
/**
* @psalm-suppress ArgumentTypeCoercion
*/
public static function pre(mixed $target, array $params, string $class, string $function, ?string $filename, ?int $lineno, ?array $span_args = [], ?array $attributes = []): void
{
static $instrumentation;
$instrumentation ??= new CachedInstrumentation(name: 'io.opentelemetry.php.with-span', schemaUrl: 'https://opentelemetry.io/schemas/1.25.0');

$name = $span_args['name'] ?? null;
if ($name === null) {
$name = empty($class)
? $function
: sprintf('%s::%s', $class, $function);
}

$kind = $span_args['span_kind'] ?? SpanKind::KIND_INTERNAL;

$span = $instrumentation
->tracer()
->spanBuilder($name)
->setSpanKind($kind)
->setAttribute('code.function', $function)
->setAttribute('code.namespace', $class)
->setAttribute('code.filepath', $filename)
->setAttribute('code.lineno', $lineno)
->setAttributes($attributes ?? [])
->startSpan();
$context = $span->storeInContext(Context::getCurrent());
Context::storage()->attach($context);
}

public static function post(mixed $target, array $params, mixed $result, ?Throwable $exception): void
{
$scope = Context::storage()->scope();
$scope?->detach();

if (!$scope || $scope->context() === Context::getCurrent()) {
return;
}

$span = Span::fromContext($scope->context());
if ($exception) {
$span->recordException($exception, ['exception.escaped' => true]);
$span->setStatus(StatusCode::STATUS_ERROR, $exception->getMessage());
}

$span->end();
}
}
100 changes: 100 additions & 0 deletions tests/Unit/API/Instrumentation/WithSpanHandlerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
<?php

declare(strict_types=1);

namespace OpenTelemetry\Tests\Unit\API\Instrumentation;

use ArrayObject;
use OpenTelemetry\API\Instrumentation\Configurator;
use OpenTelemetry\API\Instrumentation\WithSpanHandler;
use OpenTelemetry\API\Trace\SpanKind;
use OpenTelemetry\Context\ScopeInterface;
use OpenTelemetry\SDK\Trace\ImmutableSpan;
use OpenTelemetry\SDK\Trace\SpanExporter\InMemoryExporter;
use OpenTelemetry\SDK\Trace\SpanProcessor\SimpleSpanProcessor;
use OpenTelemetry\SDK\Trace\TracerProvider;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;

#[CoversClass(WithSpanHandler::class)]
class WithSpanHandlerTest extends TestCase
{
private ScopeInterface $scope;
private ArrayObject $storage;

public function setUp(): void
{
$this->storage = new ArrayObject();
$tracerProvider = new TracerProvider(
new SimpleSpanProcessor(
new InMemoryExporter($this->storage)
)
);

$this->scope = Configurator::create()
->withTracerProvider($tracerProvider)
->activate();
}

public function tearDown(): void
{
$this->scope->detach();
}

public function test_creates_span_with_all_values(): void
{
$name = 'foo';
$kind = SpanKind::KIND_CLIENT;
$attributes = ['foo' => 'bar'];
WithSpanHandler::pre(
null,
[],
'My\\Class',
'some_function',
'a_file.php',
99,
['name' => $name, 'span_kind' => $kind],
$attributes,
);
$this->assertCount(0, $this->storage);
WithSpanHandler::post(null, [], null, null);

$this->assertCount(1, $this->storage);
/** @var ImmutableSpan $span */
$span = $this->storage->offsetGet(0);

$this->assertSame($name, $span->getName());
$this->assertSame($kind, $span->getKind());
$this->assertSame([
'code.function' => 'some_function',
'code.namespace' => 'My\Class',
'code.filepath' => 'a_file.php',
'code.lineno' => 99,
'foo' => 'bar',
], $span->getAttributes()->toArray());
}

#[DataProvider('defaultsProvider')]
public function test_defaults(string $class, string $function, string $expected): void
{
$this->assertCount(0, $this->storage);
WithSpanHandler::pre(null, [], $class, $function, null, null, [], []);
WithSpanHandler::post(null, [], null, null);

$this->assertCount(1, $this->storage);
/** @var ImmutableSpan $span */
$span = $this->storage->offsetGet(0);

$this->assertSame($expected, $span->getName());
$this->assertSame(SpanKind::KIND_INTERNAL, $span->getKind());
}

public static function defaultsProvider(): array
{
return [
['My\\Class', 'foo', 'My\\Class::foo'],
['', 'foo', 'foo'],
];
}
}