PHP (OpenTelemetry)
It adds OpenTelemetry to your PHP service and checks that data arrives. How the setup skill works
Instrument a PHP application with the OpenTelemetry PHP SDK and export traces, logs and metrics to Traceway over OTLP/HTTP.
This guide is for plain PHP and frameworks without a guide of their own. The example uses Slim 4. Symfony and Laravel have their own guides.
With the opentelemetry PHP extension installed, the request spans, route names and exceptions come from an auto-instrumentation package, and the SDK is configured entirely from environment variables. If you cannot install an extension, see Without the Extension.
Requirements
- PHP 8.2 or newer and Composer.
- The
opentelemetryextension, for auto-instrumentation. Check withphp --ri opentelemetry. - A Traceway project created with framework OpenTelemetry, and that project's token.
Install
Install the extension the way your platform does it. This page was checked on a PHP build that already had it compiled in, so these commands come from the OpenTelemetry PHP documentation and were not run here:
pecl install opentelemetry
# then add to php.ini: extension=opentelemetryIn the official Docker images, install-php-extensions opentelemetry does both steps.
Then add the packages:
{
"name": "example/my-php-service",
"type": "project",
"require": {
"php": "^8.2",
"slim/slim": "^4.15",
"slim/psr7": "^1.8",
"monolog/monolog": "^3.13",
"guzzlehttp/guzzle": "^8.6",
"open-telemetry/sdk": "^1.18",
"open-telemetry/exporter-otlp": "^1.6",
"open-telemetry/opentelemetry-auto-slim": "^1.5",
"open-telemetry/opentelemetry-logger-monolog": "^1.3"
},
"autoload": {
"psr-4": {"App\\": "src/"}
},
"config": {
"allow-plugins": {
"php-http/discovery": false,
"tbachert/spi": true
}
}
}composer installopen-telemetry/opentelemetry-auto-slimcreates the request span. Composer refuses to install it without the extension (requires ext-opentelemetry * but it is not present). The OpenTelemetry project publishes the same kind of package for other frameworks and for PDO, cURL and PSR-18 clients.guzzlehttp/guzzleis the HTTP client the exporter sends with. The SDK installs without one and only fails at runtime withNo PSR-17 url factory found.- The exporter encodes protobuf in pure PHP. If the
protobufextension is installed it is used instead, with no code change.
Configure
The SDK reads all of this from the process environment.
export OTEL_PHP_AUTOLOAD_ENABLED=true
export OTEL_SERVICE_NAME=my-php-service
export OTEL_RESOURCE_ATTRIBUTES="service.version=1.0.0"
export OTEL_EXPORTER_OTLP_ENDPOINT=https://cloud.tracewayapp.com/api/otel
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer your-project-token"
export OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=delta
OTEL_PHP_AUTOLOAD_ENABLED=trueis the switch. Without it the SDK never starts: nothing is exported and nothing is logged.
OTEL_EXPORTER_OTLP_ENDPOINTtakes the base URL. The exporter appends/v1/traces,/v1/metricsand/v1/logsitself.OTEL_SERVICE_NAMEbecomes the Server Name on every endpoint, task and issue. Version travels inOTEL_RESOURCE_ATTRIBUTES. There is noOTEL_SERVICE_VERSIONvariable.http/protobufis the default. Do not set the protocol togrpc: Traceway has no gRPC listener, and the SDK then switches itself off withTransport factory not defined for protocol: grpc.
Two things about where the variables live, on PHP-FPM:
- FPM clears the environment of its workers. With the default
clear_env = yesthe variables never reach your code. Set them in the pool file withenv[NAME] = value, or setclear_env = no. - Quote booleans in INI files.
env[OTEL_PHP_AUTOLOAD_ENABLED] = truewithout quotes becomes1, and the SDK stays off withInvalid boolean value "1" interpreted as "false". Write"true".
Instrument the Application
<?php
declare(strict_types=1);
use App\CleanupJob;
use Monolog\Level;
use Monolog\Logger;
use OpenTelemetry\API\Globals;
use OpenTelemetry\Contrib\Logs\Monolog\Handler as OpenTelemetryHandler;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
require __DIR__ . '/../vendor/autoload.php';
$logger = new Logger('app');
$logger->pushHandler(new OpenTelemetryHandler(Globals::loggerProvider(), Level::Info));
$app = AppFactory::create();
$app->addRoutingMiddleware();
$app->addErrorMiddleware(false, true, true, $logger);
$app->get('/users/{id}', function (Request $request, Response $response, array $args) use ($logger) {
$id = $args['id'];
$logger->info("looking up user $id");
$span = Globals::tracerProvider()->getTracer('app')->spanBuilder('load-user')->startSpan();
$scope = $span->activate();
try {
$user = ['id' => $id, 'name' => "User $id"];
} finally {
$scope->detach();
$span->end();
}
$response->getBody()->write(json_encode($user));
return $response->withHeader('Content-Type', 'application/json');
});
$app->get('/boom', function () {
throw new RuntimeException('boom: something went wrong');
});
$app->get('/run-job', function (Request $request, Response $response) {
$cleaned = CleanupJob::run();
$response->getBody()->write(json_encode(['cleaned' => $cleaned]));
return $response->withHeader('Content-Type', 'application/json');
});
$app->run();<?php
declare(strict_types=1);
namespace App;
use OpenTelemetry\API\Globals;
use OpenTelemetry\API\Trace\SpanKind;
use OpenTelemetry\API\Trace\StatusCode;
use Throwable;
final class CleanupJob
{
public const NAME = 'cleanup-expired-sessions';
public static function run(): int
{
$span = Globals::tracerProvider()->getTracer('app')
->spanBuilder(self::NAME)
->setSpanKind(SpanKind::KIND_CONSUMER)
->setParent(false)
->startSpan();
$scope = $span->activate();
try {
$cleaned = 7;
Globals::meterProvider()->getMeter('app')
->createCounter('app.sessions_cleaned')
->add($cleaned, ['job' => self::NAME]);
return $cleaned;
} catch (Throwable $e) {
$span->recordException($e);
$span->setStatus(StatusCode::STATUS_ERROR, $e->getMessage());
throw $e;
} finally {
$scope->detach();
$span->end();
}
}
}Run it with the variables from Configure set:
php -S 127.0.0.1:8080 public/index.phpThere is no SDK setup code. Globals::tracerProvider(), Globals::meterProvider() and Globals::loggerProvider() return the providers the SDK built from the environment.
Keep
addErrorMiddleware(). With the extension and OPcache enabled, an uncaught exception that reaches the top of a Slim application without the error middleware aborted the PHP process (zend_mm_heap corrupted) on the build this page was checked with. With the middleware in place it does not happen, and the exception is recorded as an Issue.
What Arrives With No Application Code
| Traceway | Where it comes from |
|---|---|
| Endpoints, grouped by route pattern | opentelemetry-auto-slim names the request span from the Slim route: $app->get('/users/{id}', ...) becomes GET /users/{id} |
| Status codes, including 500 on an unhandled exception | The same package |
| Issues with the PHP stack trace | Exceptions that reach Slim's error middleware |
Do not name routes you want grouped by pattern: ->setName('user.show') changes the endpoint to GET user.show.
Logs
Logs need one line of code. Push the OpenTelemetry handler onto your Monolog logger, as index.php does:
$logger->pushHandler(new OpenTelemetryHandler(Globals::loggerProvider(), Level::Info));Every record written during a request then carries that request's trace id. Passing the logger to addErrorMiddleware also sends Slim's own error record for a failed request.
Background Tasks
A job appears under Tasks when its span has kind CONSUMER. A root span with the default kind is dropped. CleanupJob::run() shows the shape:
$span = Globals::tracerProvider()->getTracer('app')
->spanBuilder('cleanup-expired-sessions')
->setSpanKind(SpanKind::KIND_CONSUMER)
->setParent(false)
->startSpan();The span name is the task name, so keep it stable. setParent(false) makes the job the root of its own trace when it is started from inside a request. In PHP a job is more often a command, and the same class runs from the command line:
<?php
declare(strict_types=1);
use App\CleanupJob;
require __DIR__ . '/../vendor/autoload.php';
echo 'cleaned ', CleanupJob::run(), PHP_EOL;php bin/run-job.phpCustom Metrics
Globals::meterProvider()->getMeter('app')
->createCounter('app.sessions_cleaned')
->add(7, ['job' => 'cleanup-expired-sessions']);The counter appears in metric discovery as app.sessions_cleaned, with job as a tag you can group by. The Slim instrumentation records no http.server.* metrics, so there is nothing to switch off.
When Telemetry Is Sent
PHP handles one request per process run, and the SDK follows that: spans, logs and metrics are all sent in shutdown functions when the request ends. That has three consequences.
- The export is part of the request's lifetime. On PHP-FPM the client waits for it unless you call
fastcgi_finish_request()after$app->run(). The worker stays busy until the export is done either way.OTEL_EXPORTER_OTLP_TIMEOUTis in milliseconds and defaults to 10 seconds. OTEL_METRIC_EXPORT_INTERVALhas no effect. Metrics leave once, at the end of the request or command.- A long-running worker sends nothing until it exits, unless it flushes. Call
forceFlush()on the three providers after each job, and keep thedeltatemporality line from Configure: with the default, a worker that flushes after every job re-sends its running total each time.
Without the Extension
On hosting where you cannot install ext-opentelemetry, everything on this page still works except the automatic request span. Remove open-telemetry/opentelemetry-auto-slim from composer.json and create the span yourself in a middleware:
<?php
declare(strict_types=1);
namespace App;
use OpenTelemetry\API\Globals;
use OpenTelemetry\API\Trace\SpanKind;
use OpenTelemetry\API\Trace\StatusCode;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Slim\Exception\HttpException;
use Slim\Routing\RouteContext;
use Throwable;
final class ServerSpanMiddleware implements MiddlewareInterface
{
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$method = $request->getMethod();
$route = RouteContext::fromRequest($request)->getRoute()?->getPattern();
$parent = Globals::propagator()->extract($request->getHeaders());
$span = Globals::tracerProvider()->getTracer('app')
->spanBuilder(trim("$method $route"))
->setSpanKind(SpanKind::KIND_SERVER)
->setParent($parent)
->setAttribute('http.request.method', $method)
->setAttribute('http.route', $route)
->setAttribute('url.path', $request->getUri()->getPath())
->setAttribute('url.scheme', $request->getUri()->getScheme())
->startSpan();
$scope = $span->storeInContext($parent)->activate();
try {
$response = $handler->handle($request);
$status = $response->getStatusCode();
return $response;
} catch (Throwable $e) {
$status = $e instanceof HttpException ? $e->getCode() : 500;
if ($status >= 500) {
$span->recordException($e);
}
throw $e;
} finally {
$span->setAttribute('http.response.status_code', $status);
if ($status >= 500) {
$span->setStatus(StatusCode::STATUS_ERROR);
}
$scope->detach();
$span->end();
}
}
}Add it before the routing middleware, so that it runs after the route is known and inside the error middleware:
$app = AppFactory::create();
$app->add(new App\ServerSpanMiddleware());
$app->addRoutingMiddleware();
$app->addErrorMiddleware(false, true, true, $logger);The endpoint rows are the same. Two differences from the extension: a request that matches no route gets no span, and Slim's own error log record has no trace id.
Verify It Worked
Start the application, then send a few requests:
curl localhost:8080/users/101
curl localhost:8080/users/102
curl localhost:8080/users/103
curl localhost:8080/boom
curl localhost:8080/run-jobSet the dashboard time picker to the last 15 minutes and check:
- Endpoints. One row
GET /users/{id}with a count of 3, andGET /boomwith status 500. - Issues.
RuntimeException: boom: something went wrongwith its stack trace. - Logs. Three
looking up userlines, each linked to its trace. - Tasks.
cleanup-expired-sessions. - Metrics.
app.sessions_cleanedin metric discovery.
Nothing at all, with no error anywhere? OTEL_PHP_AUTOLOAD_ENABLED is not reaching PHP. On FPM, check clear_env and the quotes first.