Raygun4php
PHP provider for Raygun
Install / Use
/learn @MindscapeHQ/Raygun4phpREADME
Raygun4PHP
Raygun.com provider for PHP 7.2+
See v1.8 documentation for PHP v5.3+ support
Installation
Raygun4PHP uses Guzzle to handle the transmission of data to the Raygun API. Having cURL installed is recommended, but is not required, as Guzzle will use a PHP stream wrapper if cURL is not installed.
With Composer
Composer is a package management tool for PHP which automatically fetches dependencies and also supports autoloading - this is a low-impact way to get Raygun4PHP into your site.
1. If you use a *nix environment, follow the instructions to install Composer. Windows users can run this installer to automatically add it to the Path.
2. Inside your project's root directory create a composer.json file, containing:
{
"require": {
"mindscape/raygun4php": "^2.0"
}
}
3. From your shell run php composer.phar install (*nix) or composer install (Windows). This will download Raygun4PHP and create the appropriate autoload data.
4. Then in a PHP file just add:
require_once 'vendor/autoload.php';
and the library will be imported ready for use.
Usage
You can automatically send both PHP errors and object-oriented exceptions to Raygun. The RaygunClient requires an HTTP transport (e.g. Guzzle or other PSR-7 compatible interface).
There are Guzzle-based asynchronous and synchronous transport classes in the provider, or you can use your own.
Asynchronous transport
This is an example of basic usage for asynchronous sending of errors and exceptions:
<?php
namespace {
require_once 'vendor/autoload.php';
use GuzzleHttp\Client;
use Raygun4php\RaygunClient;
use Raygun4php\Transports\GuzzleAsync;
$httpClient = new Client([
'base_uri' => 'https://api.raygun.com',
'timeout' => 2.0,
'headers' => [
'X-ApiKey' => 'INSERT_API_KEY_HERE'
]
]);
$transport = new GuzzleAsync($httpClient);
$raygunClient = new RaygunClient($transport);
set_error_handler(function($errno, $errstr, $errfile, $errline) use ($raygunClient) {
$raygunClient->SendError($errno, $errstr, $errfile, $errline);
});
set_exception_handler(function($exception) use ($raygunClient) {
$raygunClient->SendException($exception);
});
register_shutdown_function(function() use ($raygunClient) {
$lastError = error_get_last();
if (!is_null($lastError)) {
[$type, $message, $file, $line] = $lastError;
$raygunClient->SendError($type, $message, $file, $line);
}
});
register_shutdown_function([$transport, 'wait']);
}
Synchronous transport
For synchronous transport, use the snippet above but replace use Raygun4php\Transports\GuzzleAsync; with:
use Raygun4php\Transports\GuzzleSync;
And replace $transport = new GuzzleAsync($httpClient); with:
$transport = new GuzzleSync($httpClient);
Remove this line:
register_shutdown_function([$transport, 'wait']);
Note that if you are placing it inside a file with a namespace of your choosing, the above code should be declared to be within the global namespace (thus the namespace { } is required). You will also need whichever require statement as above (autoload or manual) before the $raygunClient instantiation.
Copy your application's API key from the Raygun app, and paste it into the X-ApiKey header field of the HTTP client.
If the handlers reside in their own file, just import it in every file where you'd like exceptions and errors to be sent, and they will be delivered to Raygun.
Configuration
Proxies
A URL can be set as the proxy property on the HTTP Client:
// ...
$httpClient = new Client([
'base_uri' => 'https://api.raygun.com',
'proxy' => 'http://someproxy:8080',
'headers' => [
'X-ApiKey' => 'INSERT_API_KEY_HERE'
]
]);
See Guzzle's proxy documentation for more options.
Debugging with a logger
We recommend using a logger which is compatible with the PSR-3 LoggerInterface (e.g. Monolog).
Expanding on the Asynchronous transport example above, you can set a logger to be used by the transport like so:
// ...
use Monolog\Handler\FirePHPHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
// ...
$logger = new Logger('my_logger');
$logger->pushHandler(new StreamHandler(__DIR__ . '/debug.log'));
$logger->pushHandler(new FirePHPHandler());
// Create $httpClient ...
$transport = new GuzzleAsync($httpClient);
$transport->setLogger($logger);
$raygunClient = new RaygunClient($transport);
// Set error handlers ...
Response codes
- 202: Message received by Raygun API correctly
- 400: Bad Request. This may indicate an invalid payload - please contact Raygun if you continue to see this.
- 403: Invalid API key. Copy the API key from the Raygun app setup instructions or application settings
Version numbers
You can transmit the version number of your PHP project along with the message by calling SetVersion() on your RaygunClient after it is instantiated - this is optional but recommended as the version number is considered to be first-class data for a message.
$raygunClient = new RaygunClient($transport);
$raygunClient->SetVersion('1.0.0.0');
Adding Tags
Tags can be added to error data to provide extra information and to help filtering errors within Raygun.
They are provided as an array of strings or numbers passed as the 5th argument to the SendError function and as the 2nd argument to the SendException function.
The declaration of the exception and error handlers for adding tags to each payload could look something like this:
<?php
// ...
$raygunClient = new RaygunClient($transport);
$tags = ['staging-environment', 'machine-4'];
set_error_handler(function($errno, $errstr, $errfile, $errline) use ($raygunClient, $tags) {
$raygunClient->SendError($errno, $errstr, $errfile, $errline, $tags);
});
set_exception_handler(function($exception) use ($raygunClient, $tags) {
$raygunClient->SendException($exception, $tags);
});
register_shutdown_function(function() use ($raygunClient, $tags) {
$lastError = error_get_last();
if (!is_null($lastError)) {
[$type, $message, $file, $line] = $lastError;
$raygunClient->SendError($type, $message, $file, $line, $tags);
}
});
// ...
You can add tags when manually sending a handled exception like so:
try {
// Do something questionable...
} catch(Exception $exception) {
$raygunClient->SendException($exception, ['handled-exception']);
}
Affected user tracking
You can call $raygunClient->SetUser, passing in some or all of the following data, which will be used to provide an affected user count and reports:
$raygunClient->SetUser($user = 'email_or_unique_identifier', $firstName = 'Example', $fullName = 'Example User', $emailAddress = 'test@example.com', $isAnonymous = false, $uuid = 'abc123');
$user should be a unique identifier which is used to identify your users. If you set this to their email address, be sure to also set the $email parameter too.
This feature and values are optional if you wish to disable it for privacy concerns. To do so, pass true in as the second parameter to the RaygunClient constructor.
// Disable user tracking:
$raygunClient = new RaygunClient($transport, true);
Note that this data is stored as cookies. If you do not call SetUser the default is to store a random UUID to represent the user.
This feature can be used in CLI mode by calling SetUser() at the start of your session.
Custom error grouping
Control of how error instances are grouped together can be achieved by passing a callback to the SetGroupingKey method on the client. If the callback returns a string, ideally 100 characters or less, errors matching that key will be grouped together, overriding the default automatic grouping. If the callback returns a non-string value then that error will be grouped automatically.
$raygunClient->SetGroupingKey(function($payload, $stackTrace) {
// Inspect the above parameters and return a hash from the properties ...
return $payload->Details->Error->Message; // Naive message-based grouping only
});
Filtering Sensitive Data
Some error data will be too sensitive to transmit to an external service, such as credit card details or passwords. Since this data is very application specific, Raygun doesn't filter out anything by default. You can configure to either replace or otherwise transform specific values based on their keys. These transformations apply to form data ($_POST), custom user data, HTTP headers, and environment data ($_SERVER). It does not filter the URL or its $_GET parameters, or custom message strings. Since Raygun doesn't log method arguments in stack traces, those don't need filtering. All key comparisons are case insensitive.
$raygunClient->setFilterParams([
'password' => true,
'creditcardnumber' => true,
'ccv' => true,
'php_auth_pw' => true, // filters basic auth from $_SERVER
]);
// Example input: ['Username' => 'myuser','Password' => 'secret']
// Example output: ['Username' => 'myuser','Password' => '[filtered]
