Menu
Grafana Cloud

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:

  1. A PHP development environment 8.0+.
  2. PECL.
  3. Composer.

Install the SDK

Install the latest release of the OpenTelemetry PHP extension:

sh
pecl install opentelemetry

Install the protobuf extension for improved OTLP exporter performance:

sh
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:

sh
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:

php
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:

  1. Use a PSR-3 compatible logger such as monolog.
  2. Add auto-instrumentation for PSR-3 Loggers to automatically collect logs.

To add auto-instrumentation for psr3-loggers add the following composer dependency:

sh
composer require open-telemetry/opentelemetry-auto-psr3

Now when you use your logger, OpenTelemetry automatically collects the logs:

php
/** @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:

sh
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.

sh
php -S localhost:8080

Example application

See the Rolldice service for a complete example setup.

Next steps

  1. Create a free Grafana Cloud account
  2. Configure your telemetry data destination:
    1. Grafana Cloud OTLP endpoint: for a quick local development and testing setup
    2. OpenTelemetry Collector: for a robust and scalable production setup
  3. Observe your services in Application Observability

Resources

  1. PHP OpenTelemetry documentation
  2. opentelemetry package on PECL
  3. opentelemetry-php-instrumentation on GitHub