PHP installation
ranetrace/ranetrace-php is the framework-agnostic PHP SDK. It captures errors, log records, custom events and browser JavaScript errors, buffers them to a local file spool, and ships them to the Ranetrace API in batches.
Using Laravel? Install ranetrace/ranetrace-laravel instead. It wires the same capture into the framework for you.
Requirements
From the package's composer.json:
- PHP ^8.4
ext-curlandext-jsonmonolog/monolog^3.0 andpsr/log^3.0
1. Install the package
composer require ranetrace/ranetrace-php
2. Add your key to your environment
RANETRACE_ENABLED=true
RANETRACE_KEY=your-key-here
RANETRACE_KEY authenticates with the API, and nothing is captured while it is missing. RANETRACE_ENABLED is the master switch and defaults to true; set it to false to turn every feature off.
Every config key falls back to a RANETRACE_* environment variable, read from $_ENV, $_SERVER or getenv() in that order. So the key can come from the environment, or you can pass it in code.
3. Bootstrap the SDK
Build the SDK once, as early in your bootstrap as you can, and keep the instance around:
use Ranetrace\Php\Ranetrace;
$ranetrace = Ranetrace::init([
'key' => 'your-key-here',
'environment' => 'production',
]);
Ranetrace::init() remembers the instance, so code that cannot be handed the object can reach it with Ranetrace::instance() (which returns null when init() has not run). If you would rather own the instance yourself, new Ranetrace([...]) builds one without touching the static.
Every option is optional except the key. Values not passed fall back to their environment variable, then to the default:
| Config key | Environment variable | Default |
|---|---|---|
enabled |
RANETRACE_ENABLED |
true |
key |
RANETRACE_KEY |
empty |
base_url |
RANETRACE_BASE_URL |
https://api.ranetrace.com/v1 |
environment |
RANETRACE_ENVIRONMENT |
APP_ENV if set, else production |
project_root |
RANETRACE_PROJECT_ROOT |
the directory above vendor/, found via Composer's autoloader |
buffer_path |
RANETRACE_BUFFER_PATH |
ranetrace-buffer inside the system temp directory |
framework |
RANETRACE_FRAMEWORK |
none |
framework_version |
RANETRACE_FRAMEWORK_VERSION |
none |
fingerprint_salt |
RANETRACE_FINGERPRINT_SALT |
falls back to your API key |
flush_on_shutdown |
RANETRACE_FLUSH_ON_SHUTDOWN |
true |
user_resolver |
config only | none |
A malformed value is a mistake you can still fix, so it fails loudly: a non-string key or a non-callable user_resolver throws an InvalidArgumentException from the constructor. Everything that happens later, while capturing, is caught and dropped instead.
4. Register the error handlers
Error tracking is on by default, but nothing installs PHP's handlers for you:
$ranetrace->registerErrorHandlers();
This is the equivalent of the Laravel package's Ranetrace::handles($exceptions) wiring. It installs an exception handler and a shutdown handler, and it keeps whatever your application registered before it. See PHP error tracking for what that covers and what it deliberately leaves alone.
5. Verify the install
vendor/bin/ranetrace-test
The command sends one test error (Test exception from Ranetrace) and one test event (test_event) straight to the API, and prints what the API answered for each, then the buffer path, what is waiting in the buffer and any pauses:
Ranetrace test
Key abcd... (RANETRACE_KEY)
API https://api.ranetrace.com/v1
errors accepted
events accepted
Buffer /tmp/ranetrace-buffer
Waiting nothing
Pauses none
Open your website in Ranetrace to see what was accepted.
It exits 0 when the API accepted at least one of the two items, and 1 otherwise. The test items go beside the buffer, never into it, and no answer sets a pause, so a failed test leaves nothing behind for your real traffic. Each run does leave the two test items on your website in Ranetrace.
The API stores the same error once per 5 minutes, so a second run within 5 minutes reports the error as accepted, not stored: the API stores the same error once per 5 minutes and skips an error you set to ignored. Other answers a type's line can show:
refused: the API answered 401 (Unauthenticated). Check RANETRACE_KEY: the API does not accept the key. The event is then not sent, and its line readsnot sent: the key was refused.failed: could not reach <base url> (<reason>): no answer came back from the API. The reason in brackets is the network error.
Like the flush below, the command reads its configuration from the environment only. Without RANETRACE_KEY there it sends nothing, exits 1, and says:
RANETRACE_KEY is not set in this command's environment, so nothing is captured or sent. This command reads the environment only: a key your application loads from a .env file or sets in its bootstrap does not reach it.
An application that sets the key in its bootstrap, or loads it from a .env file, runs the same check from its own console, once the SDK is initialised:
echo Ranetrace\Php\Ranetrace::instance()->sendTest()->render();
That report names each setting by its config key rather than its environment variable.
The buffer and flushing
Captured items are written to a local file spool, one JSON file per type, under buffer_path. The spool is drained by a flush, which is the only place the SDK talks to the API.
There are two ways to flush, and they are safe to use together because the spool is locked and drained atomically.
On shutdown, automatically. flush_on_shutdown is true by default, so every PHP process drains the buffer as it exits. This is what makes the SDK work in the simplest possible deployment, with nothing scheduled.
From cron, on a schedule. The package ships a small binary that flushes once and exits:
* * * * * /path/to/your-app/vendor/bin/ranetrace-flush >/dev/null 2>&1
Every minute is the right cadence: the API accepts 60 requests per minute per endpoint for each website, and one run sends at most one batch per type. Pass --type=errors, --type=events, --type=logs or --type=javascript_errors to drain one type only.
The command reads its configuration entirely from the RANETRACE_* environment, because a cron entry has no application bootstrap to read a config array from. A key your application loads from a .env file in its bootstrap, or sets there, does not reach the cron job, so the cron job needs RANETRACE_KEY in its own environment. Without it the flush takes nothing from the buffer, sets no pause, prints one line on stderr and exits 1:
ranetrace-flush: RANETRACE_KEY is not set in this command's environment, so nothing is sent. This command reads the environment only: a key your application loads from a .env file or sets in its bootstrap does not reach it. Set it in the cron job's environment.
A site switched off with RANETRACE_ENABLED=false, with nothing waiting in the buffer, stays quiet and exits 0. Otherwise the command prints nothing on success and exits 0, and it exits 1 when it could not run, or could not use the buffer (see below).
The cron line above discards the command's output, so run the command once by hand, as the cron job's user and with the cron job's environment, to see whether it can send. It prints nothing and exits 0 when it has a key and can use the buffer.
The cron job also tells Ranetrace that it runs. The SDK sends nothing while the buffer is empty, so after each flush the command sends a heartbeat, at most one every 5 minutes, with the SDK's name and version and nothing else. The flush at the end of a request never sends one, so a site without the cron job sends no heartbeat and is never judged by one.
Ranetrace watches the heartbeat once it has kept arriving for 10 minutes. After 30 minutes without one it shows the application as Stopped reporting: you get one alert, the website's dashboard card says so, and its Errors, Logs and Events pages say since when. With flush_on_shutdown on, captured data still arrives as PHP processes exit. With it off, nothing arrives until the cron job runs again. Check that the cron job still runs, as the user your web server runs as, with RANETRACE_KEY in its environment. About 10 minutes after it runs again you get "Application is reporting again".
Cron is worth setting up on anything busier than a low-traffic site. Draining on shutdown ships telemetry at the pace of your traffic, so on a quiet site captured data waits in the spool until the next request flushes it. Nothing is lost while it waits: the spool is kept until it is delivered, and only batch.max_buffer_size (5000 items per type) bounds it, dropping the oldest items past that. Cron makes it arrive promptly.
Buffer path on multi-worker hosts
The default buffer path lives in the system temp directory, which is fine for a single machine where every PHP process can read the same files. Two situations need an explicit path:
RANETRACE_BUFFER_PATH=/var/www/shared/ranetrace-buffer
-
Your web processes and your cron job run as different users. The buffer is for one user, so run the cron job as the user your web processes run as. The SDK asks for mode
0770when it creates the directory and does not force a mode against the umask of the process that creates it: under the usual022the directory ends up0750and its files0644. The directory is what keeps the captured payloads from other users, so a second user cannot write to it. A flush run as another user drains what it can, then prints one line on stderr and exits1:ranetrace-flush: cannot write to the buffer in [/path] as user [deploy]: the lock file errors.lock is not writable. Run this command as the user your web server runs as.The user name is there only where the
posixextension is loaded. The line can also say that the buffer path is not a directory this user can write to, or that a buffer file is not readable.vendor/bin/ranetrace-testreports the same problem under itsBufferline. -
Your application runs on more than one machine. Each machine keeps its own spool and flushes it independently. That works, but every machine then needs a flush path of its own, whether that is the shutdown flush or its own cron entry.
The SDK also writes its own diagnostics into this directory, as a daily internal-YYYY-MM-DD.log file, so it is the first place to look when something is not arriving.
Applications on a framework
The SDK never guesses what it is running inside. If your application is on a framework, name it so error reports and log records say where they came from:
use Ranetrace\Php\Ranetrace;
use Symfony\Component\HttpKernel\Kernel;
$ranetrace = Ranetrace::init([
'key' => getenv('RANETRACE_KEY') ?: '',
'framework' => 'Symfony',
'framework_version' => Kernel::VERSION,
]);
Both keys are optional and both default to nothing, which reads as "not said" rather than "no framework".
Two other keys exist for the same reason. project_root is the directory reported file paths are made relative to; it is found through Composer's autoloader, which is right for almost every install. environment is the deployment environment name, taken from APP_ENV when you have one.
A complete example
A minimal bootstrap with all four features wired up:
<?php
require __DIR__.'/../vendor/autoload.php';
use Monolog\Logger;
use Ranetrace\Php\Ranetrace;
$ranetrace = Ranetrace::init([
'key' => getenv('RANETRACE_KEY') ?: '',
'environment' => getenv('APP_ENV') ?: 'production',
'logging' => ['enabled' => true],
'javascript_errors' => ['enabled' => true],
'user_resolver' => static function (): ?array {
$user = currentUser();
return $user === null ? null : ['id' => $user->id, 'email' => $user->email];
},
]);
$ranetrace->registerErrorHandlers();
$logger = new Logger('app');
$logger->pushHandler($ranetrace->monologHandler());
// Mount the JavaScript error relay wherever your router sends this path.
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_SERVER['REQUEST_URI'] === '/ranetrace/js-errors') {
$ranetrace->relay()->handle();
exit;
}
And in your layout, before </body>:
<?= $ranetrace->javascriptSnippet(['endpoint' => '/ranetrace/js-errors']) ?>