perfbase/laravel
Composer 安装命令:
composer require perfbase/laravel
包简介
A Laravel extension for the Perfbase profiling tool.
关键字:
README 文档
README
Perfbase for Laravel
Laravel integration for Perfbase.
This package is a thin adapter over perfbase/php-sdk. It wires Laravel request, Artisan command, and queue job lifecycles into the SDK and leaves trace transport, submission, and extension handling to the shared SDK.
What it profiles
- HTTP requests when the Perfbase middleware is installed
- Artisan commands through Laravel console events
- Queue jobs through Laravel queue events
- Manual custom spans through the
Perfbasefacade or injected SDK client
Requirements
- PHP
7.4to8.5 - Laravel
8.x,9.x,10.x,11.x,12.x, or13.x ext-jsonext-zlibext-perfbase
Installation
Install the package from Packagist:
composer require perfbase/laravel:^1.0
Install the native Perfbase extension if it is not already available:
bash -c "$(curl -fsSL https://cdn.perfbase.com/install.sh)"
Restart PHP-FPM, Octane workers, Horizon workers, or your web server after installing the extension.
Publish the config file:
php artisan vendor:publish --tag="perfbase-config"
Add the minimum environment variables:
PERFBASE_ENABLED=true PERFBASE_API_KEY=your_api_key_here PERFBASE_SAMPLE_RATE=0.1
HTTP middleware
HTTP profiling is enabled only when the middleware is present.
For Laravel 8 to 10, add it to app/Http/Kernel.php:
protected $middleware = [ // ... \Perfbase\Laravel\Middleware\PerfbaseMiddleware::class, ];
Or attach it to a middleware group:
protected $middlewareGroups = [ 'web' => [ // ... \Perfbase\Laravel\Middleware\PerfbaseMiddleware::class, ], ];
For Laravel 11+, register it in bootstrap/app.php:
use Illuminate\Foundation\Application; use Illuminate\Foundation\Configuration\Middleware; use Perfbase\Laravel\Middleware\PerfbaseMiddleware; return Application::configure(dirname(__DIR__)) ->withMiddleware(function (Middleware $middleware) { $middleware->append(PerfbaseMiddleware::class); }) ->create();
Artisan command and job profiling do not need middleware. They are wired through the package service provider.
Configuration
Published config lives at config/perfbase.php.
return [ 'enabled' => env('PERFBASE_ENABLED', false), 'debug' => env('PERFBASE_DEBUG', false), 'log_errors' => env('PERFBASE_LOG_ERRORS', true), 'api_key' => env('PERFBASE_API_KEY'), 'sample_rate' => env('PERFBASE_SAMPLE_RATE', 0.1), 'profile_http_status_codes' => [...range(200, 299), ...range(500, 599)], 'timeout' => env('PERFBASE_TIMEOUT', 5), 'proxy' => env('PERFBASE_PROXY'), 'flags' => env('PERFBASE_FLAGS', \Perfbase\SDK\FeatureFlags::DefaultFlags), 'include' => [ 'http' => ['.*'], 'artisan' => ['.*'], 'jobs' => ['.*'], ], 'exclude' => [ 'http' => [], 'artisan' => ['queue:work'], 'jobs' => [], ], ];
Environment variables
| Variable | Default | Purpose |
|---|---|---|
PERFBASE_ENABLED |
false |
Global on/off switch |
PERFBASE_API_KEY |
null |
Perfbase API key |
PERFBASE_SAMPLE_RATE |
0.1 |
Sampling rate from 0.0 to 1.0 |
PERFBASE_DEBUG |
false |
Re-throw profiling exceptions |
PERFBASE_LOG_ERRORS |
true |
Log profiling failures when debug is off |
PERFBASE_TIMEOUT |
5 |
Trace submission timeout in seconds |
PERFBASE_PROXY |
null |
Optional outbound proxy |
PERFBASE_FLAGS |
FeatureFlags::DefaultFlags |
Perfbase extension feature flags |
profile_http_status_codes is configured in config/perfbase.php. The default [...range(200, 299), ...range(500, 599)] submits successful responses and server errors, while dropping common noisy client responses such as 404. Add codes such as 404 if you want to keep them.
Feature flags
use Perfbase\SDK\FeatureFlags; 'flags' => FeatureFlags::DefaultFlags; 'flags' => FeatureFlags::AllFlags; 'flags' => FeatureFlags::TrackCpuTime | FeatureFlags::TrackPdo;
Common flags:
UseCoarseClockTrackCpuTimeTrackMemoryAllocationTrackPdoTrackHttpTrackCachesTrackMongodbTrackElasticsearchTrackQueuesTrackAwsSdkTrackFileOperationsTrackFileCompilationTrackFileDefinitionsTrackExceptions
Include and exclude filters
Filters are split by context: http, artisan, and jobs.
'include' => [ 'http' => ['GET /api/*', 'POST /checkout', 'admin.users.*'], 'artisan' => ['migrate*', 'app:*'], 'jobs' => ['App\\Jobs\\Important*'], ], 'exclude' => [ 'http' => [ '/up', '/sanctum/csrf-cookie', '/telescope', '/telescope/*', '/horizon', '/horizon/*', '/pulse', '/pulse/*', '/livewire', '/livewire/*', '/_ignition', '/_ignition/*', 'OPTIONS *', 'GET /health*', ], 'artisan' => ['queue:work', 'horizon:*'], 'jobs' => ['App\\Jobs\\NoisyDebugJob'], ],
Supported filter styles:
- Wildcards like
GET /api/* - Route names like
admin.users.* - Regex patterns like
/^POST \/checkout/ - Command patterns like
queue:* - Job class patterns like
App\\Jobs\\* - Controller or action strings matched through Laravel's string matcher
The published config excludes common Laravel framework-noise routes by default: /up, /sanctum/csrf-cookie, telescope/*, horizon/*, pulse/*, livewire/*, /_ignition/*, and all OPTIONS requests. Remove any of those entries from exclude.http if you want to profile them.
How it behaves
HTTP requests
PerfbaseMiddleware creates an HttpTraceLifecycle for the current request.
By default, only HTTP responses with a status code in profile_http_status_codes are submitted. The published config ships with [...range(200, 299), ...range(500, 599)].
HTTP include/exclude filters can match Laravel route names as well as URIs and controller/action strings.
Recorded attributes include:
source=httpactionhttp_methodhttp_urlhttp_status_codeuser_ipuser_agentuser_idwhen availableenvironmentapp_versionhostnamephp_version
Artisan commands
The service provider listens to Laravel console events and creates a ConsoleTraceLifecycle.
Recorded attributes include:
source=artisanactionexit_codeexceptionwhen presentenvironmentapp_versionhostnamephp_version
Queue jobs
The service provider listens to queue worker events and creates a QueueTraceLifecycle.
Recorded attributes include:
source=jobsactionqueueconnectionexceptionwhen presentenvironmentapp_versionhostnamephp_version
Manual spans
Use the facade when you want custom spans inside your own application code:
use Perfbase\Laravel\Facades\Perfbase; Perfbase::startTraceSpan('custom-operation', [ 'operation_type' => 'data_processing', 'record_count' => '1000', ]); Perfbase::setAttribute('processing_method', 'batch'); Perfbase::setAttribute('memory_usage', (string) memory_get_usage()); try { processLargeDataset(); Perfbase::setAttribute('status', 'success'); } catch (\Exception $e) { Perfbase::setAttribute('status', 'error'); Perfbase::setAttribute('error_message', $e->getMessage()); throw $e; } finally { Perfbase::stopTraceSpan('custom-operation'); } $result = Perfbase::submitTrace(); if (!$result->isSuccess()) { logger()->warning('Perfbase trace submission failed', [ 'status' => $result->getStatus(), 'message' => $result->getMessage(), 'status_code' => $result->getStatusCode(), ]); }
Note that Perfbase trace attributes are string values. Cast integers and booleans before passing them to setAttribute().
Dependency injection
You can inject the SDK client directly:
use Perfbase\SDK\Perfbase; class DataProcessingService { /** @var Perfbase */ private $perfbase; public function __construct(Perfbase $perfbase) { $this->perfbase = $perfbase; } public function processData(array $data): array { $this->perfbase->startTraceSpan('data-processing', [ 'record_count' => (string) count($data), 'data_type' => 'user_records', ]); try { $result = $this->performProcessing($data); $this->perfbase->setAttribute('processed_count', (string) count($result)); return $result; } finally { $this->perfbase->stopTraceSpan('data-processing'); } } }
User-specific request profiling
If your authenticated user model implements Perfbase\Laravel\Interfaces\ProfiledUser, HTTP request profiling will respect shouldBeProfiled().
use Perfbase\Laravel\Interfaces\ProfiledUser; class User extends Authenticatable implements ProfiledUser { public function shouldBeProfiled(): bool { return $this->isAdmin() || $this->isBetaTester(); } }
If the authenticated user does not implement ProfiledUser, the package falls back to normal request filtering rules.
Facade methods
| Method | Description |
|---|---|
startTraceSpan($name, $attributes = []) |
Start a named span |
stopTraceSpan($name) |
Stop a named span |
setAttribute($key, $value) |
Add a string attribute to the current trace |
setFlags($flags) |
Change extension feature flags |
submitTrace() |
Submit trace data and return a SubmitResult |
getTraceData($spanName = '') |
Get raw trace data |
reset() |
Clear the current trace session |
isExtensionAvailable() |
Check whether the native extension is loaded |
Error handling
The package is designed to fail open in normal operation. When profiling cannot start or trace submission fails, your Laravel request, command, or job should continue running.
Use PERFBASE_DEBUG=true if you want profiling exceptions to surface during local development.
Testing
In application tests, it is often simplest to disable profiling:
<env name="PERFBASE_ENABLED" value="false"/>
You can also mock the facade:
use Perfbase\Laravel\Facades\Perfbase; public function test_something() { Perfbase::shouldReceive('startTraceSpan')->once(); Perfbase::shouldReceive('stopTraceSpan')->once(); // ... }
Troubleshooting
Extension not loaded
php -m | grep perfbase php --ini bash -c "$(curl -fsSL https://cdn.perfbase.com/install.sh)"
High overhead
- Lower
PERFBASE_SAMPLE_RATE - Use
FeatureFlags::UseCoarseClock - Disable feature flags you do not need
- Narrow your
includefilters and expand yourexcludefilters
Documentation
Full documentation is available at perfbase.com/docs.
- Docs: perfbase.com/docs
- Issues: github.com/perfbaseorg/laravel/issues
- Support: support@perfbase.com
License
Apache-2.0. See LICENSE.txt.
perfbase/laravel 适用场景与选型建议
perfbase/laravel 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1.08k 次下载、GitHub Stars 达 1, 最近一次更新时间为 2024 年 11 月 04 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「profiling」 「laravel」 「Perfbase」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 perfbase/laravel 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 perfbase/laravel 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 perfbase/laravel 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Quick profiling of your code for Laravel
Excimetry PHP package. Bridge between ext-eximer and open telemetry
An SDK for sending profiling data to Perfbase
MongoQP is a frontend for MongoDB's query profiler collection.
PHPUnit loggers to profile tests.
Alfabank REST API integration
统计信息
- 总下载量: 1.08k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 1
- 点击次数: 22
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: Apache-2.0
- 更新时间: 2024-11-04