-
Notifications
You must be signed in to change notification settings - Fork 223
Expand file tree
/
Copy pathWithSpanHandler.php
More file actions
66 lines (55 loc) · 2.17 KB
/
WithSpanHandler.php
File metadata and controls
66 lines (55 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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.40.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.name', $class !== null ? $class . '::' . $function : $function)
->setAttribute('code.file.path', $filename)
->setAttribute('code.line.number', $lineno)
->setAttribute('code.column.number', $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();
}
}