Drupal integration for Perfbase.
This module is a thin adapter over perfbase/php-sdk. It connects Drupal runtime lifecycles to the Perfbase profiler and ingestion API without implementing its own transport, trace format, or profiler runtime.
This module currently profiles:
- HTTP requests
- Drupal cron runs
- Core Queue API worker execution
- Symfony console commands dispatched through Drupal's event dispatcher (see Console for the Drush caveat)
This module does not currently add dedicated support for:
- Messenger workers
- Batch API execution
- Install/update hook specific instrumentation
- Drupal-specific render/entity/cache enrichment beyond what the Perfbase extension already captures
- PHP
>=8.1 <8.7(Drupal 11 itself requires PHP 8.3+) - Drupal
^10.3 || ^11.0 - Composer
- Perfbase PHP extension installed and enabled
- A valid Perfbase API key
Install the module with Composer:
composer require perfbase/drupalEnable the module:
drush en perfbaseOr enable it through the Drupal admin UI.
The module stores runtime configuration in Drupal config as perfbase.settings.
Configuration is resolved in this order:
- module defaults
- saved Drupal config
settings.phpoverrides
That resolution logic is implemented in src/Config/ConfigResolver.php.
The settings form is available at:
/admin/config/development/perfbase
The form is implemented in src/Form/PerfbaseSettingsForm.php.
At minimum, production installs should set:
enabled: trueapi_key: <your Perfbase API key>
Recommended starting values:
sample_rate: 0.1profile_http: trueexclude_admin_routes: trueprofile_console: falseprofile_cron: trueprofile_queue: truedebug: falselog_errors: true
Use settings.php for deployment-time overrides that should win over saved config:
$settings['perfbase'] = [
'enabled' => TRUE,
'api_key' => 'pb_live_xxxxx',
'api_url' => 'https://ingress.perfbase.cloud',
'sample_rate' => 0.10,
'exclude_admin_routes' => TRUE,
'profile_http_status_codes' => [...range(200, 299), ...range(500, 599)],
'profile_http' => TRUE,
'profile_console' => FALSE,
'profile_cron' => TRUE,
'profile_queue' => TRUE,
'environment' => 'production',
'app_version' => '2026.04.08',
];Values set here always win over saved config. The settings form shows them as disabled and leaves them untouched when it saves, so an API key kept in settings.php is never copied into stored configuration or into a config export. Remove the override to edit a value through the form.
| Key | Type | Default | Notes |
|---|---|---|---|
enabled |
bool | false |
Module is effectively disabled until this is true and api_key is non-empty |
debug |
bool | false |
Re-throws profiler exceptions instead of failing open |
log_errors |
bool | true |
Logs profiler/runtime failures when not in debug mode |
api_key |
string | '' |
Required for submission |
api_url |
string | https://ingress.perfbase.cloud |
Override for self-hosted or non-default receiver endpoints |
timeout |
int | 10 |
Submission timeout in seconds; invalid or non-positive values fall back to 10 |
proxy |
string | '' |
Optional outbound proxy URL (http, https, socks5, socks5h) |
flags |
int | FeatureFlags::DefaultFlags (16775265) |
Perfbase feature flags bitmask; see Feature Flags |
sample_rate |
float | 0.1 |
Value from 0.0 to 1.0 |
exclude_admin_routes |
bool | true |
Drop traces for routes with Drupal's _admin_route option (/admin/* paths and entity edit forms) |
profile_http_status_codes |
int[] | 200-299, 500-599 |
Only HTTP responses with these status codes are submitted; add 404 if you want to keep not-found traces |
profile_http |
bool | true |
Enables HTTP request profiling |
profile_console |
bool | false |
Enables console / Drush profiling |
profile_cron |
bool | true |
Enables cron profiling |
profile_queue |
bool | true |
Enables core Queue API profiling |
environment |
string | '' |
Optional environment label |
app_version |
string | '' |
Optional application version label |
include |
map | * per context |
Include filters for http, console, cron, and queue |
exclude |
map | empty per context | Exclude filters for http, console, cron, and queue |
Persisted defaults are defined in config/install/perfbase.settings.yml, and runtime fallbacks are resolved in src/Config/ConfigResolver.php.
Values from settings.php may be strings (for example read from environment variables): timeout and flags accept integer strings, and an empty api_url or proxy falls back to the default / no proxy.
flags is passed to the SDK and the Perfbase extension. The admin form shows one checkbox per flag. The default is the SDK's FeatureFlags::DefaultFlags: every feature except per-function CPU time and memory allocation tracking.
| Flag | Notes |
|---|---|
UsePreciseClock |
Opt-in. High-resolution wall timing on hosts without a fast default clock |
TrackCpuTime |
Opt-in. Per-function CPU time (adds a syscall per call) |
TrackMemoryAllocation |
Per-function memory allocation |
TrackExceptions, TrackErrors |
Exception throws and PHP errors/warnings |
TrackMagicMethods |
Magic method call counts |
TrackFileCompilation, TrackOpcache |
include/require compilation and OPcache statistics |
TrackPdo, TrackMongodb, TrackElasticsearch |
Database and search queries |
TrackCaches |
Redis and Memcached |
TrackHttp |
Outbound HTTP (cURL, Guzzle) |
TrackMail, TrackFileOperations, TrackStreams, TrackProc, TrackProcessList |
Mail, file I/O, stream errors (PHP 8.6+), process execution and a process-list snapshot |
A mask of 0, or one containing only the opt-in flags, means "every feature except the opt-in flags" plus any opt-in flags set. Any mask containing a regular flag enables exactly those features. Sites still on the old shipped default (8145) are moved to the current default by the perfbase_post_update_refresh_default_flags post-update (drush updatedb).
Each supported context has include and exclude filters:
httpconsolecronqueue
Supported filter forms:
*or.*for match-all/regex/expressions- shell-style glob patterns
Example:
include:
http:
- 'GET /admin/*'
console:
- 'cache:*'
cron:
- 'cron.run'
queue:
- 'my_worker'
exclude:
http:
- 'GET /healthz'
console:
- 'list'Matching is implemented in src/Support/FilterMatcher.php.
HTTP profiling is wired through Symfony kernel events:
kernel.requestkernel.responsekernel.exceptionkernel.terminate
The trace starts on kernel.request (priority 1000), before routing. Route-based decisions are applied when the request terminates: the admin-route exclusion, include filters (which may name routes), and the status-code allowlist all decide whether the trace is submitted or discarded. Exclude filters that already match the request path skip profiling up front.
Implementation:
Console command profiling subscribes to Symfony console events on Drupal's event dispatcher:
console.commandconsole.errorconsole.terminate
Drush dispatches console events through its own event dispatcher, not Drupal's, so Drush commands are not traced as console commands even with profile_console: true. Cron and queue work started from Drush (drush cron, drush queue:run) is still traced by the cron and queue integrations.
Implementation:
Cron profiling is implemented by decorating Drupal’s cron service and wrapping run().
Implementation:
Queue profiling is implemented by replacing plugin.manager.queue_worker with a Perfbase-aware queue worker manager and wrapping worker instances returned by createInstance().
Implementation:
src/Queue/PerfbaseQueueWorkerManager.phpsrc/Queue/ProfiledQueueWorker.phpsrc/Lifecycle/QueueItemLifecycle.php
Queue item exceptions (including SuspendQueueException and RequeueException) are rethrown unchanged, even in debug mode.
Drupal nests these contexts: automated cron runs during an HTTP request's kernel.terminate, and cron processes queue items. Only the outermost context traces; nested work is recorded as part of its trace. For example, queue items processed by drush cron are part of the cron trace, while drush queue:run produces one trace per queue item.
The module keeps span names and action values low-cardinality. Span names are fixed by lifecycle (http, cli, cron, and queue; earlier releases named the console span artisan), while the action attribute carries the route, command, cron task, or queue worker identity:
- HTTP action is
METHOD route-path(for exampleGET /node/{node}), falling back to the route name or a normalized path with numeric and UUID segments replaced - console action uses the command name
- cron action is
cron.run - queue action uses the queue worker plugin ID
http_url is the full request URL including the query string, passed through the SDK's UrlSanitizer: values of credential-looking parameters (token, password, api_key, signature, nonce, session IDs, email, and similar) are replaced with REDACTED, and user info and fragments are dropped. The hash in one-time login links (/user/reset/{uid}/{timestamp}/{hash}) is also redacted. action never contains the query string.
Common attributes include:
sourceactionenvironmentapp_versionhostnamephp_version
HTTP requests also attach:
http_methodhttp_urlhttp_status_codeuser_ipuser_agentuser_idfor authenticated users (from Drupal'scurrent_user)drupal.route_namewhen available
Queue traces also attach queue (the worker plugin ID); console traces attach exit_code and drupal.command. Any trace whose work threw attaches exception (the message).
By default, traces for Drupal admin routes are discarded. You can disable that with exclude_admin_routes: false if you want admin traffic included.
By default, only responses in the configured profile_http_status_codes allowlist are submitted. The runtime default is 200-299 plus 500-599, so 404s are dropped unless you add them explicitly.
Naming logic is implemented in src/Support/SpanNaming.php.
- The module is fail-open in production mode: profiling and submission errors (including
PerfbaseExceptionfromsubmitTrace()) are caught and never change the response or the application's exception. - After a failed or rejected submission the trace data is discarded, so it cannot leak into the next trace of a long-running process.
- Profiling errors are logged when
log_errorsis enabled. - Debug mode rethrows exceptions so integration issues are visible during development.
- Submission occurs through the shared SDK and uses the installed Perfbase PHP extension.
Shared runtime services:
src/Runtime/PerfbaseFactory.phpsrc/Runtime/ActiveLifecycleRegistry.phpsrc/Support/ErrorHandler.php
- Use
settings.phpfor API keys and deployment-controlled overrides. - Keep
debugdisabled in production. - Start with a conservative
sample_rateand increase as needed. - Exclude health checks, noisy admin paths, or high-volume commands if they are not useful to retain.
- If you use a custom receiver, set
api_urlexplicitly.
Current package validation includes:
- PHPUnit
- PHPStan level 9 with Drupal-aware analysis
- PHPCS with Drupal coding standards
- GitHub Actions on Drupal
10.xwith PHP8.1, and Drupal11.xwith PHP8.3,8.5and8.6 - Non-blocking GitHub Actions rows for the upcoming Drupal
11.5(PHP8.3) and Drupal12.0(PHP8.5and8.6) pre-releases. A failing pre-release row does not fail the workflow.
The current suite focuses on unit coverage plus fixture-backed wiring checks. It is not yet a full booted-Drupal kernel test suite. Passing against a pre-release does not by itself declare support for it: the drupal/core constraint and core_version_requirement are widened only once a release has been checked on a real site.
Install dependencies:
composer installRun the full validation stack:
composer run lintRun individual checks:
composer run test
composer run phpstan
composer run phpcs
XDEBUG_MODE=coverage vendor/bin/phpunit -c phpunit.xml --coverage-textThis package keeps Drupal scaffold output for fixture-based validation under tests/fixtures/drupal/web.
Full documentation is available at perfbase.com/docs.
- Docs: perfbase.com/docs
- Issues: github.com/perfbaseorg/drupal/issues
- Support: support@perfbase.com
Apache-2.0. See LICENSE.txt.