Instrument a PHP application
Follow this article to install the upstream OpenTelemetry distribution for PHP and auto-instrument your application running on Linux for Grafana Cloud Application Observability.
Alternatively, if you need a instrumentation solution for PHP supported by Grafana, use Grafana Beyla.
Before you begin
The is the first step to get telemetry data into Application Observability, you need:
- A PHP development environment 8.0+.
- PECL.
- Composer.
Install the SDK
Install the latest release of the OpenTelemetry PHP extension:
pecl install opentelemetry
Install the protobuf extension for improved OTLP exporter performance:
pecl install protobuf
Add the extensions to php.ini
:
extension=protobuf.so
[opentelemetry]
extension=opentelemetry.so
Install required packages via composer
, including auto-instrumentation for the Slim framework:
composer require \
open-telemetry/sdk \
open-telemetry/exporter-otlp \
open-telemetry/opentelemetry-auto-slim \
php-http/guzzle7-adapter
If Composer autoloading is not already enabled, modify the application entrypoint to include this line:
require __DIR__ . '/vendor/autoload.php';
Note
A number of popular PHP libraries have auto-instrumention packages available, including Laravel and WordPress. For a full list refer to the OpenTelemetry website.
Collect logs
To collect logs for your PHP application:
- Use a PSR-3 compatible logger such as monolog.
- Add auto-instrumentation for PSR-3 Loggers to automatically collect logs.
To add auto-instrumentation for psr3-loggers add the following composer dependency:
composer require open-telemetry/opentelemetry-auto-psr3
Now when you use your logger, OpenTelemetry automatically collects the logs:
/** @var \Psr\Log\LoggerInterface $logger */
$logger->info('This message will be sent to Grafana Cloud via OTLP');
Instrument your application
Export the following environment variables before running your application to configure auto-instrumentation:
export OTEL_PHP_AUTOLOAD_ENABLED=true
export OTEL_TRACES_EXPORTER=otlp
export OTEL_METRICS_EXPORTER=otlp
export OTEL_LOGS_EXPORTER=otlp
export OTEL_PROPAGATORS=baggage,tracecontext
Test your instrumentation
To test if you successfully instrumented your application and are producing telemetry data, run the application. The console output should print references to metrics and logs.
php -S localhost:8080
Example application
See the Rolldice service for a complete example setup.
Next steps
- Create a free Grafana Cloud account
- Configure your telemetry data destination:
- Grafana Cloud OTLP endpoint: for a quick local development and testing setup
- OpenTelemetry Collector: for a robust and scalable production setup
- Observe your services in Application Observability