ivoglent/ elastic-apm-php-agent
Elastic APM 的 PHP 代理
6.6.13
2019-10-23 03:00 UTC
Requires
- php: >= 7.1
- ext-curl: *
- ext-json: *
- guzzlehttp/guzzle: 6.*
- ralouphie/getallheaders: ^2.0.5 || ^3.0.0
- ramsey/uuid: ^3.7
Requires (Dev)
Suggests
- ext-xdebug: Required for processing of request headers
This package is auto-updated.
Last update: 2024-09-23 13:56:08 UTC
README
注意 1: 这不是官方的 Elastic APM 代理,PHP APM 代理是一个 社区开发的代理。注意 2: 这是来自 原始仓库 的分支,但我已经修改了很多内容,所以不能创建 PR 合并它 :). 不管怎样,感谢 @philkra。
这是 Elastic.co APM 产品的 PHP 代理:[Elastic APM](https://elastic.ac.cn/solutions/apm)。它仅支持 v2 APM API。
安装
推荐通过 Composer 安装代理。
运行以下 composer 命令
php composer.phar require ivoglent/elastic-apm-php-agent
安装后,您需要引入 Composer 的自动加载器
require 'vendor/autoload.php';
使用
使用最小配置初始化代理
$config = [ 'name' => 'Service Name', 'secretToken' => 'APM api token', 'transport' => [ 'host' => 'APM server host', 'config' => [ 'base_uri' => 'base URL to APM server', ], ], 'framework' => [ 'name' => 'Framework Name', 'version' => 'Framework version', ] ]; $contexts = [ 'user' => [ 'id' => 'USER_ID', 'username' => 'USER_NAME', 'email' => 'EMAIL' ] ]; $agent = new \PhilKra\Agent($config, $contexts);
捕获错误和异常
代理可以捕获所有实现了 Throwable
接口(https://php.ac.cn/manual/en/class.throwable.php)的错误和异常。
$error = $agent->factory()->newError(new \Exception()); $error->setTransaction($transaction); $error->setParentId($transaction->getId()); $agent->register($error);
事务和分段的用法
添加分段([事务分段](https://elastic.ac.cn/guide/en/apm/server/current/transactions.html#transaction-spans))很简单。请参阅文档以了解您的具体需求。以下是一个添加 MySQL 分段的示例。
//Create APM agent $agent = new \PhilKra\Agent($config, $contexts); //Create new transaction $transaction = $agent->factory()->newTransaction($transactionName, $transactionType); //Start current transaction $transaction->start(); //Create new span $span = $agent->factory()->newSpan($spanName, $spanType, $spanAction); $span->setTransaction($transaction); $span->setParentId($transaction->getId()); //Start span $span->start(); //Add sql context to span $context = new \PhilKra\Traces\SpanContexts\SpanContext(); $context->statement = 'SQL Query String'; $trace->addContext('db', $context); //Stop span $span->stop(); //Register span to agent $agent->register($span); //Stop transaction $transaction->stop(); //Register transaction to agent $agent->register($transaction); //Send all data to APM server $agent->send();
测试
vendor/bin/phpunit
知识库
禁用 CLI 代理
如果您想动态地禁用代理以用于混合 SAPI,请使用以下代码片段。
'active' => PHP_SAPI !== 'cli'
针对 Laravel APM 提供程序
'active' => PHP_SAPI !== 'cli' && env('ELASTIC_APM_ACTIVE', false)
感谢 @jblotus,(philkra/elastic-apm-laravel#19)