bethinkpl/elastic-apm-laravel

一个用于将 Elastic APM 7.x 集成到 Laravel 的包

7.6.0 2021-02-26 12:12 UTC

README

Laravel 包,由 https://github.com/philkra/elastic-apm-php-agent 库提供支持,自动处理事务和错误/异常。如果使用 Illuminate\Support\Facades\Auth,则将用户 ID 添加到上下文中。已测试与 Laravel 6.* 和 philkra/elastic-apm-php-agent 版本 7.x 一起使用。

安装

composer require bethinkpl/elastic-apm-laravel

在 wnl-platform 中使用本地代码而不是已发布的包

cd wnl-platform/vendor/bethinkpl/
rm -rf elastic-apm-laravel
ln -s ../../../elastic-apm-laravel ./elastic-apm-laravel

请确保使用绝对路径。

附加功能

  • X-Requested-By HTTP 请求头值设置为 APM 事务字段 labels.requested_by(当 X-Requested-With: XMLHttpRequest 设置时使用 end-user-ajax 值)
  • 对报告给 APM 的交易进行采样
  • 使用 GuzzleHttp 库执行的 HTTP 请求的跟踪。只需将以下中间件添加到您的 Guzzle 客户端
<?php

use PhilKra\ElasticApmLaravel\Providers\ElasticApmServiceProvider;
use GuzzleHttp\HandlerStack;

$handler = HandlerStack::create();
$handler->push(ElasticApmServiceProvider::getGuzzleMiddleware());

// create your client with 'handler' option passed

中间件

Laravel

注册为(例如)全局中间件,以便在每个请求时调用。 https://laravel.net.cn/docs/5.6/middleware#global-middleware

app/Http/Kernel.php 中注册中间件

protected $middleware = [
    // ... more middleware
    \PhilKra\ElasticApmLaravel\Middleware\RecordTransaction::class,
];

Lumen

bootstrap/app.php 中注册 PhilKra\ElasticApmLaravel\Middleware\RecordTransaction::class 作为中间件

$app->middleware([
    PhilKra\ElasticApmLaravel\Middleware\RecordTransaction::class
]);

服务提供者

Laravel

无需手动注册服务提供者。它将由 package discovery 自动注册。

Lumen

bootstrap/app.php 中注册 \PhilKra\ElasticApmLaravel\Providers\ElasticApmServiceProvider::class 作为服务提供者

$app->register(\PhilKra\ElasticApmLaravel\Providers\ElasticApmServiceProvider::class);

跨度

Laravel

通过依赖注入容器提供 Transaction 对象,可以在应用程序的任何位置启动新的跨度。跨度将在结束时自动将自己添加到事务中。

// Use any normal Laravel method of resolving the dependency
$transaction = app(\PhilKra\ElasticApmLaravel\Apm\Transaction::class);

$span = $transaction->startNewSpan('My Span', 'app.component_name');

// do some stuff

$span->end();

Lumen

挂起

错误/异常处理

Laravel

app/Exceptions/Handler 中,向 report 方法添加以下内容

ElasticApm::captureThrowable($exception);
ElasticApm::send();

确保在文件顶部导入外观

use ElasticApm;

Lumen

尚未测试。

代理配置

Laravel

默认配置中支持以下环境变量

您还可以发布 elastic-apm.php 配置文件以更改其他设置

php artisan vendor:publish --tag=config

发布后,打开 config/elastic-apm.php 文件并查看各种设置。

Laravel 测试设置

Laravel 提供了支持使用 PHPUnit 运行单元测试和功能测试的类。在大多数情况下,您可能希望显式禁用 APM 进行测试,因为它默认启用。有关更多信息,请参阅 Laravel 文档(https://laravel.net.cn/docs/5.7/testing)。

由于 APM 代理使用严格的布尔类型检查其活动状态,您必须确保您的 APM_ACTIVE 值是布尔值 false,而不是简单的假值。完成此操作的最佳方式是创建一个 .env.testing 文件,并包括 APM_ACTIVE=false,以及您测试所需的任何其他环境设置。此文件可以安全地包含在您的版本控制中。