更新时间:2026-11-03 GMT+08:00
使用OpenTelemetry上报PHP应用数据
APM兼容OpenTelemetry协议,支持直接接收通过OpenTelemetry SDK或Agent上报的链路追踪数据。本文介绍如何使用OpenTelemetry方式,将PHP语言的应用接入APM,并上报链路追踪指标数据。
限制条件
非侵入式接入,需使用PHP 8.0以及以上版本。
环境准备
- 准备插件/工具:PHP 8.0+、PECL、Composer。
- 执行命令安装PHP、Composer。
apt update apt install -y php-pear apt install composer
- 执行命令验证环境。
pecl version composer --version
示例demo
- 初始化demo应用。
- 编写应用代码。创建index.php文件,内容如下:
<?php use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; use Slim\Factory\AppFactory; require __DIR__ . '/vendor/autoload.php'; $app = AppFactory::create(); $app->get('/rolldice', function (Request $request, Response $response) { $result = random_int(1,6); $response->getBody()->write(strval($result)); return $response; }); $app->run(); - 执行命令运行应用。
php -S localhost:8080 & curl http://localhost:8080/rolldice
非侵入式接入
- 执行命令安装必需的构建工具。
sudo apt-get install gcc make autoconf
- 执行命令使用构建安装扩展组件。
sudo apt-get install php-dev pecl install opentelemetry pecl install grpc //安装编译时间较长(20-30分钟),请耐心等待 pecl install protobuf-3.21.12 //与 PHP 8兼容
根据php需要选择对应的插件版本,比如php8.0,opentelemetry需要选择1.1.3或者之前的版本,protobuf使用3.21.0相近的版本。
- 启用扩展组件。
- 定位当前环境加载的php.ini配置文件路径,命令如下:
php --ini | grep "Configuration File"
- 在php中添加以下内容:
[opentelemetry] extension=opentelemetry.so[ [PHP] extensionxtension=grpc.so extensionextension=protobuf.so
- 定位当前环境加载的php.ini配置文件路径,命令如下:
- 执行命令验证。
php --ri opentelemetry php --ri grpc php --ri protobuf
- 执行命令安装服务框架所需的opentelemetry自动埋点的依赖。
composer config allow-plugins.php-http/discovery false composer require open-telemetry/sdk composer require open-telemetry/exporter-otlp composer require open-telemetry/transport-grpc composer require open-telemetry/opentelemetry-auto-slim composer update
- 执行命令添加云服务配置参数为环境变量中并启动。
env OTEL_EXPORTER_OTLP_ENDPOINT=http://xxx.xxx.xx.xxx:4317 \ OTEL_EXPORTER_OTLP_HEADERS=Authentication=LV***9l \ OTEL_EXPORTER_OTLP_PROTOCOL=grpc \ OTEL_PHP_AUTOLOAD_ENABLED=true \ OTEL_SERVICE_NAME=应用名称.组件名称.环境名称 \ php -S localhost:8080 &
- 执行命令触发请求。
curl -kv http://localhost:8080/rolldice

- 登录APM控制台。
- 在左侧导航栏选择“链路追踪 > 指标”。
- 在界面左侧树单击环境,单击“接口调用”,切换至接口调用页签,在接口调用页签可以查看接口调用的数据。
- 在左侧导航栏选择“链路追踪 > 调用链”,查看调用链信息。
父主题: 使用OpenTelemetry接入APM