This is a PHP extension for OpenTelemetry, to enable auto-instrumentation. It is based on zend_observer and requires php8+
The extension allows creating pre
and post
hook functions to arbitrary PHP functions and methods, which allows those methods to be wrapped with telemetry.
- PHP 8+
- OpenTelemetry PHP library
The extension can be installed in all of the usual ways:
pecl install opentelemetry
pickle can be used to install extensions that are available via http://pecl.php.net, or install directly from source code.
To install directly from source code:
php pickle.phar install --source https://github.com/open-telemetry/opentelemetry-php-instrumentation.git#1.0.0beta1
If you are using the official PHP docker images then you can use php-extension-installer
From github:
install-php-extensions open-telemetry/opentelemetry-php-instrumentation@main
Via pecl/pickle:
install-php-extensions opentelemetry[-beta|-stable|-latest]
php -m | grep opentelemetry
The following example adds an observer to the DemoClass::run
method, and provides two functions which will be run before and after the method call.
The pre
method starts and activates a span. The post
method ends the span after the observed method has finished.
Be aware of that, trivial functions are candidates for optimizations. Optimizer can optimize them out and replace user function call with more optimal set of instructions (inlining). In this case hooks will not be invoked as there will be no function.
<?php
$tracer = new Tracer(...);
OpenTelemetry\Instrumentation\hook(
DemoClass::class,
'run',
static function (DemoClass $demo, array $params, string $class, string $function, ?string $filename, ?int $lineno) use ($tracer) {
$span = $tracer->spanBuilder($class)
->startSpan();
Context::storage()->attach($span->storeInContext(Context::getCurrent()));
},
static function (DemoClass $demo, array $params, $returnValue, ?Throwable $exception) use ($tracer) {
$scope = Context::storage()->scope();
$scope?->detach();
$span = Span::fromContext($scope->context());
$exception && $span->recordException($exception);
$span->setStatus($exception ? StatusCode::STATUS_ERROR : StatusCode::STATUS_OK);
$span->end();
}
);
There are more examples in the tests directory
Invoke clang-format -i *.c *.h
before commit your changes, just for preserve formatting consistency.
See DEVELOPMENT.md and https://github.com/open-telemetry/opentelemetry-php/blob/main/CONTRIBUTING.md