Enable Custom OpenTelemetry for Your PHP Application
By default, the OpenTelemetry PHP extension we provide enables itself based on the presence of a Trace ID in an HTTP header.
However, you need to install its SDK and some optional additional instrumentation libraries into your application in order to send traces from your PHP application, or to get library- or framework-specific detail in your traces.
The OpenTelemetry SDK and its instrumentation libraries are available via Composer, and your application will need to use Composer for dependency management to take advantage of them.
At the bare minimum, you will need to run the following commands to enable and install the SDK:
composer config allow-plugins.php-http/discovery false
composer require open-telemetry/sdk open-telemetry/transport-grpc
--ignore-platform-req=ext-grpc --ignore-platform-req=ext-opentelemetry. From there, you can install additional instrumentation libraries based on your application; for a full list see Packagist.Some libraries that are often useful across applications:
|
Package |
Notes |
|---|---|
|
open-telemetry/opentelemetry-auto-curl |
Provides instrumentation for cURL operations |
|
open-telemetry/opentelemetry-auto-doctrine |
Provides instrumentation for Doctrine DBAL operations |
|
open-telemetry/opentelemetry-auto-io |
Provides instrumentation for file and network operations |
|
open-telemetry/opentelemetry-auto-io |
Provides instrumentation for file and network operations |
|
open-telemetry/opentelemetry-auto-pdo |
Provides instrumentation for PDO operations |
|
open-telemetry/opentelemetry-auto-psr3 |
Provides instrumentation for PSR-3 logging libraries, including Monolog |
|
open-telemetry/opentelemetry-auto-psr6 |
Provides instrumentation for PSR-6 caching libraries |
|
open-telemetry/opentelemetry-auto-psr14 |
Provides instrumentation for PSR-14 event dispatcher libraries |
|
mismatch/opentelemetry-auto-redis |
Provides instrumentation for the Redis extension and/or Predis client library |
Force the application to send the response
Because OpenTelemetry needs to send request trace information before the request lifecycle ends and PHP cleans up the process, you will want to ensure your application sends the response and terminates the HTTP request before OTel does its work.
Typically, this is done by calling the following function after the response is returned:
fastcgi_finish_request();
Where you do this will be dependent on your application.
For applications with a centralized front controller, you can do this after the application runs.
For example, in Mezzio or Laminas MVC applications, in your public/index.php, you can put it after the $app->run() call:
$app->run();
fastcgi_finish_request();
For a Laravel application, add it after the $app->handleRequest() line of public/index.php:
$app->handleRequest(Request::capture());
fastcgi_finish_request();