This repository was archived by the owner on Mar 23, 2021. It is now read-only.

Repository files navigation

Rollbar notifier for PHP Build Status

This library detects errors and exceptions in your application and reports them to Rollbar for alerts, reporting, and analysis.

Supported PHP versions: 5.3, 5.4, 5.5, 5.6, 7, and HHVM (currently tested on 3.6.6).

Quick start

<?phpuse \Rollbar\Rollbar;
use \Rollbar\Payload\Level;
// installs global error and exception handlers
Rollbar::init(
array(
'access_token' => ROLLBAR_TEST_TOKEN,
'environment' => 'production'
)
);
try {
thrownew \Exception('test exception');
} catch (\Exception$e) {
Rollbar::log(Level::error(), $e);
}
// Message at level 'info'
Rollbar::log(Level::info(), 'testing info level');
// With extra data (3rd arg) and custom payload options (4th arg)
Rollbar::log(
Level::info(),
'testing extra data',
array("some_key" => "some value") // key-value additional data
);
// If you want to check if logging with Rollbar was successful$response = Rollbar::log(Level::info(), 'testing wasSuccessful()');
if (!$response->wasSuccessful()) {
thrownew \Exception('logging with Rollbar failed');
}
// raises an E_NOTICE which will *not* be reported by the error handler$foo = $bar;
// will be reported by the exception handlerthrownew \Exception('testing exception handler');
?>

Installation

Using Composer (recommended)

Add rollbar/rollbar to your composer.json:

{
"require": {
"rollbar/rollbar": "~1.0.1"
}
}

Manual installation if you are not using composer.json for your project

Keep in mind, that even if you're not using composer for your project (using composer.json), you will still need composer package to install rollbar-php dependencies.

  1. If you don't have composer yet, follow these instructions to get the package: install composer. It will be needed to install dependencies.
  2. Clone git repository rollbar/rollbar-php into a your external libraries path: git clone https://github.com/rollbar/rollbar-php
  3. Install rollbar-php dependencies: cd rollbar-php && composer install && cd ..
  4. Require rollbar-php in your PHP scripts: require_once YOUR_LIBS_PATH . '/rollbar-php/vendor/autoload.php';

Setup

Add the following code at your application's entry point:

<?phpuse \Rollbar\Rollbar;
$config = array(
// required'access_token' => 'POST_SERVER_ITEM_ACCESS_TOKEN',
// optional - environment name. any string will do.'environment' => 'production',
// optional - path to directory your code is in. used for linking stack traces.'root' => '/Users/brian/www/myapp'
);
Rollbar::init($config);
?>

Be sure to replace POST_SERVER_ITEM_ACCESS_TOKEN with your project's post_server_item access token, which you can find in the Rollbar.com interface.

This will install an exception handler (with set_exception_handler) and an error handler (with set_error_handler). If you'd rather not do that:

<?php$set_exception_handler = false;
$set_error_handler = false;
Rollbar::init($config, $set_exception_handler, $set_error_handler);
?>

For Heroku Users

First, add the addon:

heroku addons:create rollbar:free

The access_token and root config variables will be automatically detected, so the config is simply:

<?phpuseRollbar\Rollbar;
Rollbar::init(array(
'environment' => 'production'
));
?>

Basic Usage

That's it! Uncaught errors and exceptions will now be reported to Rollbar.

If you'd like to report exceptions that you catch yourself:

<?phpuseRollbar\Rollbar;
useRollbar\Payload\Level;
try {
do_something();
} catch (\Exception$e) {
Rollbar::log(Level::error(), $e);
// or
Rollbar::log(Level::error(), $e, array("my" => "extra", "data" => 42));
}
?>

You can also send Rollbar log-like messages:

<?phpuseRollbar\Rollbar;
useRollbar\Payload\Level;
Rollbar::log(Level::warning(), 'could not connect to mysql server');
Rollbar::log(
Level::info(), 'Here is a message with some additional data',
array('x' => 10, 'code' => 'blue')
);
?>

Using Monolog

Here is an example of how to use Rollbar as a handler for Monolog:

useMonolog\Logger;
useRollbar\Rollbar;
useRollbar\Payload\Level;
$config = array('access_token' => 'POST_SERVER_ITEM_ACCESS_TOKEN');
// installs global error and exception handlers
Rollbar::init($config);
$log = newLogger('test');
$log->pushHandler(new \Monolog\Handler\PsrHandler(Rollbar::logger()));
try {
thrownew \Exception('exception for monolog');
} catch (\Exception$e) {
$log->error($e);
}

Configuration

Asynchronous Reporting

By default, payloads (batched or not) are sent as part of script execution. This is easy to configure but may negatively impact performance. With some additional setup, payloads can be written to a local relay file instead; that file will be consumed by rollbar-agent asynchronously. To turn this on, set the following config params:

<?php$config = array(
// ... rest of current config'handler' => 'agent',
'agent_log_location' => '/var/www'// not including final slash. must be writeable by the user php runs as.
);
?>

You'll also need to run the agent. See the rollbar-agent docs for setup instructions.

Configuration reference

All of the following options can be passed as keys in the $config array.

access_token
Your project access token.
agent_log_location
Path to the directory where agent relay log files should be written. Should not include final slash. Only used when handler is `agent`.

Default: /var/www

base_api_url
The base api url to post to.

Default: https://api.rollbar.com/api/1/

branch
Name of the current branch.

Default: master

capture_error_stacktraces
Record full stacktraces for PHP errors.

Default: true

checkIgnore
Function called before sending payload to Rollbar, return true to stop the error from being sent to Rollbar.

Default: null

Parameters:

  • $isUncaught: boolean value set to true if the error was an uncaught exception.
  • $exception: a RollbarException instance that will allow you to get the message or exception
  • $payload: an array containing the payload as it will be sent to Rollbar. Payload schema can be found at https://rollbar.com/docs/api/items_post/
$config = array(
'access_token' => '...',
'checkIgnore' => function ($isUncaught, $exception, $payload) {
if (isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'Baiduspider') !== false) {
// ignore baidu spiderreturntrue;
}
// no other ignoresreturnfalse;
};
);
Rollbar::init($config);
code_version
The currently-deployed version of your code/application (e.g. a Git SHA). Should be a string.

Default: null

enable_utf8_sanitization
set to false, to disable running iconv on the payload, may be needed if there is invalid characters, and the payload is being destroyed

Default: true

environment
Environment name, e.g. `'production'` or `'development'`

Default: 'production'

error_sample_rates
Associative array mapping error numbers to sample rates. Sample rates are ratio out of 1, e.g. 0 is "never report", 1 is "always report", and 0.1 is "report 10% of the time". Sampling is done on a per-error basis.

Default: empty array, meaning all errors are reported.

handler
Either `'blocking'` or `'agent'`. `'blocking'` uses curl to send requests immediately; `'agent'` writes a relay log to be consumed by [rollbar-agent](https://github.com/rollbar/rollbar-agent).

Default: 'blocking'

host
Server hostname.

Default: null, which will result in a call to gethostname() (or php_uname('n') if that function does not exist)

include_error_code_context
A boolean that indicates you wish to gather code context for instances of PHP Errors. This can take a while because it requires reading the file from disk, so it's off by default.

Default: false

include_exception_code_context
A boolean that indicates you wish to gather code context for instances of PHP Exceptions. This can take a while because it requires reading the file from disk, so it's off by default.

Default: false

included_errno
A bitmask that includes all of the error levels to report. E.g. (E_ERROR \| E_WARNING) to only report E_ERROR and E_WARNING errors. This will be used in combination with `error_reporting()` to prevent reporting of errors if `use_error_reporting` is set to `true`.

Default: (E_ERROR | E_WARNING | E_PARSE | E_CORE_ERROR | E_USER_ERROR | E_RECOVERABLE_ERROR)

logger
An object that has a `log($level, $message)` method. If provided, will be used by RollbarNotifier to log messages.
person
An associative array containing data about the currently-logged in user. Required: `id`, optional: `username`, `email`. All values are strings.
person_fn
A function reference (string, etc. - anything that [call_user_func()](http://php.net/call_user_func) can handle) returning an array like the one for 'person'.
root
Path to your project's root dir
scrub_fields
Array of field names to scrub out of \_POST and \_SESSION. Values will be replaced with asterisks. If overriding, make sure to list all fields you want to scrub, not just fields you want to add to the default. Param names are converted to lowercase before comparing against the scrub list.

Default: ('passwd', 'password', 'secret', 'confirm_password', 'password_confirmation', 'auth_token', 'csrf_token')

shift_function
Whether to shift function names in stack traces down one frame, so that the function name correctly reflects the context of each frame.

Default: true

timeout
Request timeout for posting to rollbar, in seconds.

Default: 3

report_suppressed
Sets whether errors suppressed with '@' should be reported or not

Default: false

use_error_reporting
Sets whether to respect current `error_reporting()` level or not

Default: false

proxy
Send data via a proxy server.

E.g. Using a local proxy with no authentication

<?php$config['proxy'] = "127.0.0.1:8080";
?>

E.g. Using a local proxy with basic authentication

<?php$config['proxy'] = array(
'address' => '127.0.0.1:8080',
'username' => 'my_user',
'password' => 'my_password'
);
?>

Default: No proxy

Example use of error_sample_rates:

<?php$config['error_sample_rates'] = array(
// E_WARNING omitted, so defaults to 1E_NOTICE => 0.1,
E_USER_ERROR => 0.5,
// E_USER_WARNING will take the same value, 0.5E_USER_NOTICE => 0.1,
// E_STRICT and beyond will all be 0.1
);
?>

Example use of person_fn:

<?phpfunctionget_current_user() {
if ($_SESSION['user_id']) {
returnarray(
'id' => $_SESSION['user_id'], // required - value is a string'username' => $_SESSION['username'], // optional - value is a string'email' => $_SESSION['user_email'] // optional - value is a string
);
}
returnnull;
}
$config['person_fn'] = 'get_current_user';
?>

Related projects

A Laravel-specific package is available for integrating with Laravel: Laravel-Rollbar

A CakePHP-specific package is avaliable for integrating with CakePHP 2.x: CakeRollbar

A Flow-specific package is available for integrating with Neos Flow: m12/flow-rollbar

Help / Support

If you run into any issues, please email us at support@rollbar.com

You can also find us in IRC: #rollbar on chat.freenode.net

For bug reports, please open an issue on GitHub.

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Added some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

Testing

Tests are in tests. To run the tests: composer test To fix code style issues: composer fix

About

Error tracking and logging from PHP to Rollbar

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
This repository was archived by the owner on Mar 23, 2021. It is now read-only.

Repository files navigation

Rollbar notifier for PHP Build Status

This library detects errors and exceptions in your application and reports them to Rollbar for alerts, reporting, and analysis.

Supported PHP versions: 5.3, 5.4, 5.5, 5.6, 7, and HHVM (currently tested on 3.6.6).

Quick start

<?phpuse \Rollbar\Rollbar;
use \Rollbar\Payload\Level;
// installs global error and exception handlers
Rollbar::init(
array(
'access_token' => ROLLBAR_TEST_TOKEN,
'environment' => 'production'
)
);
try {
thrownew \Exception('test exception');
} catch (\Exception$e) {
Rollbar::log(Level::error(), $e);
}
// Message at level 'info'
Rollbar::log(Level::info(), 'testing info level');
// With extra data (3rd arg) and custom payload options (4th arg)
Rollbar::log(
Level::info(),
'testing extra data',
array("some_key" => "some value") // key-value additional data
);
// If you want to check if logging with Rollbar was successful$response = Rollbar::log(Level::info(), 'testing wasSuccessful()');
if (!$response->wasSuccessful()) {
thrownew \Exception('logging with Rollbar failed');
}
// raises an E_NOTICE which will *not* be reported by the error handler$foo = $bar;
// will be reported by the exception handlerthrownew \Exception('testing exception handler');
?>

Installation

Using Composer (recommended)

Add rollbar/rollbar to your composer.json:

{
"require": {
"rollbar/rollbar": "~1.0.1"
}
}

Manual installation if you are not using composer.json for your project

Keep in mind, that even if you're not using composer for your project (using composer.json), you will still need composer package to install rollbar-php dependencies.

  1. If you don't have composer yet, follow these instructions to get the package: install composer. It will be needed to install dependencies.
  2. Clone git repository rollbar/rollbar-php into a your external libraries path: git clone https://github.com/rollbar/rollbar-php
  3. Install rollbar-php dependencies: cd rollbar-php && composer install && cd ..
  4. Require rollbar-php in your PHP scripts: require_once YOUR_LIBS_PATH . '/rollbar-php/vendor/autoload.php';

Setup

Add the following code at your application's entry point:

<?phpuse \Rollbar\Rollbar;
$config = array(
// required'access_token' => 'POST_SERVER_ITEM_ACCESS_TOKEN',
// optional - environment name. any string will do.'environment' => 'production',
// optional - path to directory your code is in. used for linking stack traces.'root' => '/Users/brian/www/myapp'
);
Rollbar::init($config);
?>

Be sure to replace POST_SERVER_ITEM_ACCESS_TOKEN with your project's post_server_item access token, which you can find in the Rollbar.com interface.

This will install an exception handler (with set_exception_handler) and an error handler (with set_error_handler). If you'd rather not do that:

<?php$set_exception_handler = false;
$set_error_handler = false;
Rollbar::init($config, $set_exception_handler, $set_error_handler);
?>

For Heroku Users

First, add the addon:

heroku addons:create rollbar:free

The access_token and root config variables will be automatically detected, so the config is simply:

<?phpuseRollbar\Rollbar;
Rollbar::init(array(
'environment' => 'production'
));
?>

Basic Usage

That's it! Uncaught errors and exceptions will now be reported to Rollbar.

If you'd like to report exceptions that you catch yourself:

<?phpuseRollbar\Rollbar;
useRollbar\Payload\Level;
try {
do_something();
} catch (\Exception$e) {
Rollbar::log(Level::error(), $e);
// or
Rollbar::log(Level::error(), $e, array("my" => "extra", "data" => 42));
}
?>

You can also send Rollbar log-like messages:

<?phpuseRollbar\Rollbar;
useRollbar\Payload\Level;
Rollbar::log(Level::warning(), 'could not connect to mysql server');
Rollbar::log(
Level::info(), 'Here is a message with some additional data',
array('x' => 10, 'code' => 'blue')
);
?>

Using Monolog

Here is an example of how to use Rollbar as a handler for Monolog:

useMonolog\Logger;
useRollbar\Rollbar;
useRollbar\Payload\Level;
$config = array('access_token' => 'POST_SERVER_ITEM_ACCESS_TOKEN');
// installs global error and exception handlers
Rollbar::init($config);
$log = newLogger('test');
$log->pushHandler(new \Monolog\Handler\PsrHandler(Rollbar::logger()));
try {
thrownew \Exception('exception for monolog');
} catch (\Exception$e) {
$log->error($e);
}

Configuration

Asynchronous Reporting

By default, payloads (batched or not) are sent as part of script execution. This is easy to configure but may negatively impact performance. With some additional setup, payloads can be written to a local relay file instead; that file will be consumed by rollbar-agent asynchronously. To turn this on, set the following config params:

<?php$config = array(
// ... rest of current config'handler' => 'agent',
'agent_log_location' => '/var/www'// not including final slash. must be writeable by the user php runs as.
);
?>

You'll also need to run the agent. See the rollbar-agent docs for setup instructions.

Configuration reference

All of the following options can be passed as keys in the $config array.

access_token
Your project access token.
agent_log_location
Path to the directory where agent relay log files should be written. Should not include final slash. Only used when handler is `agent`.

Default: /var/www

base_api_url
The base api url to post to.

Default: https://api.rollbar.com/api/1/

branch
Name of the current branch.

Default: master

capture_error_stacktraces
Record full stacktraces for PHP errors.

Default: true

checkIgnore
Function called before sending payload to Rollbar, return true to stop the error from being sent to Rollbar.

Default: null

Parameters:

  • $isUncaught: boolean value set to true if the error was an uncaught exception.
  • $exception: a RollbarException instance that will allow you to get the message or exception
  • $payload: an array containing the payload as it will be sent to Rollbar. Payload schema can be found at https://rollbar.com/docs/api/items_post/
$config = array(
'access_token' => '...',
'checkIgnore' => function ($isUncaught, $exception, $payload) {
if (isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'Baiduspider') !== false) {
// ignore baidu spiderreturntrue;
}
// no other ignoresreturnfalse;
};
);
Rollbar::init($config);
code_version
The currently-deployed version of your code/application (e.g. a Git SHA). Should be a string.

Default: null

enable_utf8_sanitization
set to false, to disable running iconv on the payload, may be needed if there is invalid characters, and the payload is being destroyed

Default: true

environment
Environment name, e.g. `'production'` or `'development'`

Default: 'production'

error_sample_rates
Associative array mapping error numbers to sample rates. Sample rates are ratio out of 1, e.g. 0 is "never report", 1 is "always report", and 0.1 is "report 10% of the time". Sampling is done on a per-error basis.

Default: empty array, meaning all errors are reported.

handler
Either `'blocking'` or `'agent'`. `'blocking'` uses curl to send requests immediately; `'agent'` writes a relay log to be consumed by [rollbar-agent](https://github.com/rollbar/rollbar-agent).

Default: 'blocking'

host
Server hostname.

Default: null, which will result in a call to gethostname() (or php_uname('n') if that function does not exist)

include_error_code_context
A boolean that indicates you wish to gather code context for instances of PHP Errors. This can take a while because it requires reading the file from disk, so it's off by default.

Default: false

include_exception_code_context
A boolean that indicates you wish to gather code context for instances of PHP Exceptions. This can take a while because it requires reading the file from disk, so it's off by default.

Default: false

included_errno
A bitmask that includes all of the error levels to report. E.g. (E_ERROR \| E_WARNING) to only report E_ERROR and E_WARNING errors. This will be used in combination with `error_reporting()` to prevent reporting of errors if `use_error_reporting` is set to `true`.

Default: (E_ERROR | E_WARNING | E_PARSE | E_CORE_ERROR | E_USER_ERROR | E_RECOVERABLE_ERROR)

logger
An object that has a `log($level, $message)` method. If provided, will be used by RollbarNotifier to log messages.
person
An associative array containing data about the currently-logged in user. Required: `id`, optional: `username`, `email`. All values are strings.
person_fn
A function reference (string, etc. - anything that [call_user_func()](http://php.net/call_user_func) can handle) returning an array like the one for 'person'.
root
Path to your project's root dir
scrub_fields
Array of field names to scrub out of \_POST and \_SESSION. Values will be replaced with asterisks. If overriding, make sure to list all fields you want to scrub, not just fields you want to add to the default. Param names are converted to lowercase before comparing against the scrub list.

Default: ('passwd', 'password', 'secret', 'confirm_password', 'password_confirmation', 'auth_token', 'csrf_token')

shift_function
Whether to shift function names in stack traces down one frame, so that the function name correctly reflects the context of each frame.

Default: true

timeout
Request timeout for posting to rollbar, in seconds.

Default: 3

report_suppressed
Sets whether errors suppressed with '@' should be reported or not

Default: false

use_error_reporting
Sets whether to respect current `error_reporting()` level or not

Default: false

proxy
Send data via a proxy server.

E.g. Using a local proxy with no authentication

<?php$config['proxy'] = "127.0.0.1:8080";
?>

E.g. Using a local proxy with basic authentication

<?php$config['proxy'] = array(
'address' => '127.0.0.1:8080',
'username' => 'my_user',
'password' => 'my_password'
);
?>

Default: No proxy

Example use of error_sample_rates:

<?php$config['error_sample_rates'] = array(
// E_WARNING omitted, so defaults to 1E_NOTICE => 0.1,
E_USER_ERROR => 0.5,
// E_USER_WARNING will take the same value, 0.5E_USER_NOTICE => 0.1,
// E_STRICT and beyond will all be 0.1
);
?>

Example use of person_fn:

<?phpfunctionget_current_user() {
if ($_SESSION['user_id']) {
returnarray(
'id' => $_SESSION['user_id'], // required - value is a string'username' => $_SESSION['username'], // optional - value is a string'email' => $_SESSION['user_email'] // optional - value is a string
);
}
returnnull;
}
$config['person_fn'] = 'get_current_user';
?>

Related projects

A Laravel-specific package is available for integrating with Laravel: Laravel-Rollbar

A CakePHP-specific package is avaliable for integrating with CakePHP 2.x: CakeRollbar

A Flow-specific package is available for integrating with Neos Flow: m12/flow-rollbar

Help / Support

If you run into any issues, please email us at support@rollbar.com

You can also find us in IRC: #rollbar on chat.freenode.net

For bug reports, please open an issue on GitHub.

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Added some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

Testing

Tests are in tests. To run the tests: composer test To fix code style issues: composer fix

About

Error tracking and logging from PHP to Rollbar

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
This repository was archived by the owner on Mar 23, 2021. It is now read-only.

Repository files navigation

Rollbar notifier for PHP Build Status

This library detects errors and exceptions in your application and reports them to Rollbar for alerts, reporting, and analysis.

Supported PHP versions: 5.3, 5.4, 5.5, 5.6, 7, and HHVM (currently tested on 3.6.6).

Quick start

<?phpuse \Rollbar\Rollbar;
use \Rollbar\Payload\Level;
// installs global error and exception handlers
Rollbar::init(
array(
'access_token' => ROLLBAR_TEST_TOKEN,
'environment' => 'production'
)
);
try {
thrownew \Exception('test exception');
} catch (\Exception$e) {
Rollbar::log(Level::error(), $e);
}
// Message at level 'info'
Rollbar::log(Level::info(), 'testing info level');
// With extra data (3rd arg) and custom payload options (4th arg)
Rollbar::log(
Level::info(),
'testing extra data',
array("some_key" => "some value") // key-value additional data
);
// If you want to check if logging with Rollbar was successful$response = Rollbar::log(Level::info(), 'testing wasSuccessful()');
if (!$response->wasSuccessful()) {
thrownew \Exception('logging with Rollbar failed');
}
// raises an E_NOTICE which will *not* be reported by the error handler$foo = $bar;
// will be reported by the exception handlerthrownew \Exception('testing exception handler');
?>

Installation

Using Composer (recommended)

Add rollbar/rollbar to your composer.json:

{
"require": {
"rollbar/rollbar": "~1.0.1"
}
}

Manual installation if you are not using composer.json for your project

Keep in mind, that even if you're not using composer for your project (using composer.json), you will still need composer package to install rollbar-php dependencies.

  1. If you don't have composer yet, follow these instructions to get the package: install composer. It will be needed to install dependencies.
  2. Clone git repository rollbar/rollbar-php into a your external libraries path: git clone https://github.com/rollbar/rollbar-php
  3. Install rollbar-php dependencies: cd rollbar-php && composer install && cd ..
  4. Require rollbar-php in your PHP scripts: require_once YOUR_LIBS_PATH . '/rollbar-php/vendor/autoload.php';

Setup

Add the following code at your application's entry point:

<?phpuse \Rollbar\Rollbar;
$config = array(
// required'access_token' => 'POST_SERVER_ITEM_ACCESS_TOKEN',
// optional - environment name. any string will do.'environment' => 'production',
// optional - path to directory your code is in. used for linking stack traces.'root' => '/Users/brian/www/myapp'
);
Rollbar::init($config);
?>

Be sure to replace POST_SERVER_ITEM_ACCESS_TOKEN with your project's post_server_item access token, which you can find in the Rollbar.com interface.

This will install an exception handler (with set_exception_handler) and an error handler (with set_error_handler). If you'd rather not do that:

<?php$set_exception_handler = false;
$set_error_handler = false;
Rollbar::init($config, $set_exception_handler, $set_error_handler);
?>

For Heroku Users

First, add the addon:

heroku addons:create rollbar:free

The access_token and root config variables will be automatically detected, so the config is simply:

<?phpuseRollbar\Rollbar;
Rollbar::init(array(
'environment' => 'production'
));
?>

Basic Usage

That's it! Uncaught errors and exceptions will now be reported to Rollbar.

If you'd like to report exceptions that you catch yourself:

<?phpuseRollbar\Rollbar;
useRollbar\Payload\Level;
try {
do_something();
} catch (\Exception$e) {
Rollbar::log(Level::error(), $e);
// or
Rollbar::log(Level::error(), $e, array("my" => "extra", "data" => 42));
}
?>

You can also send Rollbar log-like messages:

<?phpuseRollbar\Rollbar;
useRollbar\Payload\Level;
Rollbar::log(Level::warning(), 'could not connect to mysql server');
Rollbar::log(
Level::info(), 'Here is a message with some additional data',
array('x' => 10, 'code' => 'blue')
);
?>

Using Monolog

Here is an example of how to use Rollbar as a handler for Monolog:

useMonolog\Logger;
useRollbar\Rollbar;
useRollbar\Payload\Level;
$config = array('access_token' => 'POST_SERVER_ITEM_ACCESS_TOKEN');
// installs global error and exception handlers
Rollbar::init($config);
$log = newLogger('test');
$log->pushHandler(new \Monolog\Handler\PsrHandler(Rollbar::logger()));
try {
thrownew \Exception('exception for monolog');
} catch (\Exception$e) {
$log->error($e);
}

Configuration

Asynchronous Reporting

By default, payloads (batched or not) are sent as part of script execution. This is easy to configure but may negatively impact performance. With some additional setup, payloads can be written to a local relay file instead; that file will be consumed by rollbar-agent asynchronously. To turn this on, set the following config params:

<?php$config = array(
// ... rest of current config'handler' => 'agent',
'agent_log_location' => '/var/www'// not including final slash. must be writeable by the user php runs as.
);
?>

You'll also need to run the agent. See the rollbar-agent docs for setup instructions.

Configuration reference

All of the following options can be passed as keys in the $config array.

access_token
Your project access token.
agent_log_location
Path to the directory where agent relay log files should be written. Should not include final slash. Only used when handler is `agent`.

Default: /var/www

base_api_url
The base api url to post to.

Default: https://api.rollbar.com/api/1/

branch
Name of the current branch.

Default: master

capture_error_stacktraces
Record full stacktraces for PHP errors.

Default: true

checkIgnore
Function called before sending payload to Rollbar, return true to stop the error from being sent to Rollbar.

Default: null

Parameters:

  • $isUncaught: boolean value set to true if the error was an uncaught exception.
  • $exception: a RollbarException instance that will allow you to get the message or exception
  • $payload: an array containing the payload as it will be sent to Rollbar. Payload schema can be found at https://rollbar.com/docs/api/items_post/
$config = array(
'access_token' => '...',
'checkIgnore' => function ($isUncaught, $exception, $payload) {
if (isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'Baiduspider') !== false) {
// ignore baidu spiderreturntrue;
}
// no other ignoresreturnfalse;
};
);
Rollbar::init($config);
code_version
The currently-deployed version of your code/application (e.g. a Git SHA). Should be a string.

Default: null

enable_utf8_sanitization
set to false, to disable running iconv on the payload, may be needed if there is invalid characters, and the payload is being destroyed

Default: true

environment
Environment name, e.g. `'production'` or `'development'`

Default: 'production'

error_sample_rates
Associative array mapping error numbers to sample rates. Sample rates are ratio out of 1, e.g. 0 is "never report", 1 is "always report", and 0.1 is "report 10% of the time". Sampling is done on a per-error basis.

Default: empty array, meaning all errors are reported.

handler
Either `'blocking'` or `'agent'`. `'blocking'` uses curl to send requests immediately; `'agent'` writes a relay log to be consumed by [rollbar-agent](https://github.com/rollbar/rollbar-agent).

Default: 'blocking'

host
Server hostname.

Default: null, which will result in a call to gethostname() (or php_uname('n') if that function does not exist)

include_error_code_context
A boolean that indicates you wish to gather code context for instances of PHP Errors. This can take a while because it requires reading the file from disk, so it's off by default.

Default: false

include_exception_code_context
A boolean that indicates you wish to gather code context for instances of PHP Exceptions. This can take a while because it requires reading the file from disk, so it's off by default.

Default: false

included_errno
A bitmask that includes all of the error levels to report. E.g. (E_ERROR \| E_WARNING) to only report E_ERROR and E_WARNING errors. This will be used in combination with `error_reporting()` to prevent reporting of errors if `use_error_reporting` is set to `true`.

Default: (E_ERROR | E_WARNING | E_PARSE | E_CORE_ERROR | E_USER_ERROR | E_RECOVERABLE_ERROR)

logger
An object that has a `log($level, $message)` method. If provided, will be used by RollbarNotifier to log messages.
person
An associative array containing data about the currently-logged in user. Required: `id`, optional: `username`, `email`. All values are strings.
person_fn
A function reference (string, etc. - anything that [call_user_func()](http://php.net/call_user_func) can handle) returning an array like the one for 'person'.
root
Path to your project's root dir
scrub_fields
Array of field names to scrub out of \_POST and \_SESSION. Values will be replaced with asterisks. If overriding, make sure to list all fields you want to scrub, not just fields you want to add to the default. Param names are converted to lowercase before comparing against the scrub list.

Default: ('passwd', 'password', 'secret', 'confirm_password', 'password_confirmation', 'auth_token', 'csrf_token')

shift_function
Whether to shift function names in stack traces down one frame, so that the function name correctly reflects the context of each frame.

Default: true

timeout
Request timeout for posting to rollbar, in seconds.

Default: 3

report_suppressed
Sets whether errors suppressed with '@' should be reported or not

Default: false

use_error_reporting
Sets whether to respect current `error_reporting()` level or not

Default: false

proxy
Send data via a proxy server.

E.g. Using a local proxy with no authentication

<?php$config['proxy'] = "127.0.0.1:8080";
?>

E.g. Using a local proxy with basic authentication

<?php$config['proxy'] = array(
'address' => '127.0.0.1:8080',
'username' => 'my_user',
'password' => 'my_password'
);
?>

Default: No proxy

Example use of error_sample_rates:

<?php$config['error_sample_rates'] = array(
// E_WARNING omitted, so defaults to 1E_NOTICE => 0.1,
E_USER_ERROR => 0.5,
// E_USER_WARNING will take the same value, 0.5E_USER_NOTICE => 0.1,
// E_STRICT and beyond will all be 0.1
);
?>

Example use of person_fn:

<?phpfunctionget_current_user() {
if ($_SESSION['user_id']) {
returnarray(
'id' => $_SESSION['user_id'], // required - value is a string'username' => $_SESSION['username'], // optional - value is a string'email' => $_SESSION['user_email'] // optional - value is a string
);
}
returnnull;
}
$config['person_fn'] = 'get_current_user';
?>

Related projects

A Laravel-specific package is available for integrating with Laravel: Laravel-Rollbar

A CakePHP-specific package is avaliable for integrating with CakePHP 2.x: CakeRollbar

A Flow-specific package is available for integrating with Neos Flow: m12/flow-rollbar

Help / Support

If you run into any issues, please email us at support@rollbar.com

You can also find us in IRC: #rollbar on chat.freenode.net

For bug reports, please open an issue on GitHub.

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Added some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

Testing

Tests are in tests. To run the tests: composer test To fix code style issues: composer fix

About

Error tracking and logging from PHP to Rollbar

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
This repository was archived by the owner on Mar 23, 2021. It is now read-only.

Repository files navigation

Rollbar notifier for PHP Build Status

This library detects errors and exceptions in your application and reports them to Rollbar for alerts, reporting, and analysis.

Supported PHP versions: 5.3, 5.4, 5.5, 5.6, 7, and HHVM (currently tested on 3.6.6).

Quick start

<?phpuse \Rollbar\Rollbar;
use \Rollbar\Payload\Level;
// installs global error and exception handlers
Rollbar::init(
array(
'access_token' => ROLLBAR_TEST_TOKEN,
'environment' => 'production'
)
);
try {
thrownew \Exception('test exception');
} catch (\Exception$e) {
Rollbar::log(Level::error(), $e);
}
// Message at level 'info'
Rollbar::log(Level::info(), 'testing info level');
// With extra data (3rd arg) and custom payload options (4th arg)
Rollbar::log(
Level::info(),
'testing extra data',
array("some_key" => "some value") // key-value additional data
);
// If you want to check if logging with Rollbar was successful$response = Rollbar::log(Level::info(), 'testing wasSuccessful()');
if (!$response->wasSuccessful()) {
thrownew \Exception('logging with Rollbar failed');
}
// raises an E_NOTICE which will *not* be reported by the error handler$foo = $bar;
// will be reported by the exception handlerthrownew \Exception('testing exception handler');
?>

Installation

Using Composer (recommended)

Add rollbar/rollbar to your composer.json:

{
"require": {
"rollbar/rollbar": "~1.0.1"
}
}

Manual installation if you are not using composer.json for your project

Keep in mind, that even if you're not using composer for your project (using composer.json), you will still need composer package to install rollbar-php dependencies.

  1. If you don't have composer yet, follow these instructions to get the package: install composer. It will be needed to install dependencies.
  2. Clone git repository rollbar/rollbar-php into a your external libraries path: git clone https://github.com/rollbar/rollbar-php
  3. Install rollbar-php dependencies: cd rollbar-php && composer install && cd ..
  4. Require rollbar-php in your PHP scripts: require_once YOUR_LIBS_PATH . '/rollbar-php/vendor/autoload.php';

Setup

Add the following code at your application's entry point:

<?phpuse \Rollbar\Rollbar;
$config = array(
// required'access_token' => 'POST_SERVER_ITEM_ACCESS_TOKEN',
// optional - environment name. any string will do.'environment' => 'production',
// optional - path to directory your code is in. used for linking stack traces.'root' => '/Users/brian/www/myapp'
);
Rollbar::init($config);
?>

Be sure to replace POST_SERVER_ITEM_ACCESS_TOKEN with your project's post_server_item access token, which you can find in the Rollbar.com interface.

This will install an exception handler (with set_exception_handler) and an error handler (with set_error_handler). If you'd rather not do that:

<?php$set_exception_handler = false;
$set_error_handler = false;
Rollbar::init($config, $set_exception_handler, $set_error_handler);
?>

For Heroku Users

First, add the addon:

heroku addons:create rollbar:free

The access_token and root config variables will be automatically detected, so the config is simply:

<?phpuseRollbar\Rollbar;
Rollbar::init(array(
'environment' => 'production'
));
?>

Basic Usage

That's it! Uncaught errors and exceptions will now be reported to Rollbar.

If you'd like to report exceptions that you catch yourself:

<?phpuseRollbar\Rollbar;
useRollbar\Payload\Level;
try {
do_something();
} catch (\Exception$e) {
Rollbar::log(Level::error(), $e);
// or
Rollbar::log(Level::error(), $e, array("my" => "extra", "data" => 42));
}
?>

You can also send Rollbar log-like messages:

<?phpuseRollbar\Rollbar;
useRollbar\Payload\Level;
Rollbar::log(Level::warning(), 'could not connect to mysql server');
Rollbar::log(
Level::info(), 'Here is a message with some additional data',
array('x' => 10, 'code' => 'blue')
);
?>

Using Monolog

Here is an example of how to use Rollbar as a handler for Monolog:

useMonolog\Logger;
useRollbar\Rollbar;
useRollbar\Payload\Level;
$config = array('access_token' => 'POST_SERVER_ITEM_ACCESS_TOKEN');
// installs global error and exception handlers
Rollbar::init($config);
$log = newLogger('test');
$log->pushHandler(new \Monolog\Handler\PsrHandler(Rollbar::logger()));
try {
thrownew \Exception('exception for monolog');
} catch (\Exception$e) {
$log->error($e);
}

Configuration

Asynchronous Reporting

By default, payloads (batched or not) are sent as part of script execution. This is easy to configure but may negatively impact performance. With some additional setup, payloads can be written to a local relay file instead; that file will be consumed by rollbar-agent asynchronously. To turn this on, set the following config params:

<?php$config = array(
// ... rest of current config'handler' => 'agent',
'agent_log_location' => '/var/www'// not including final slash. must be writeable by the user php runs as.
);
?>

You'll also need to run the agent. See the rollbar-agent docs for setup instructions.

Configuration reference

All of the following options can be passed as keys in the $config array.

access_token
Your project access token.
agent_log_location
Path to the directory where agent relay log files should be written. Should not include final slash. Only used when handler is `agent`.

Default: /var/www

base_api_url
The base api url to post to.

Default: https://api.rollbar.com/api/1/

branch
Name of the current branch.

Default: master

capture_error_stacktraces
Record full stacktraces for PHP errors.

Default: true

checkIgnore
Function called before sending payload to Rollbar, return true to stop the error from being sent to Rollbar.

Default: null

Parameters:

  • $isUncaught: boolean value set to true if the error was an uncaught exception.
  • $exception: a RollbarException instance that will allow you to get the message or exception
  • $payload: an array containing the payload as it will be sent to Rollbar. Payload schema can be found at https://rollbar.com/docs/api/items_post/
$config = array(
'access_token' => '...',
'checkIgnore' => function ($isUncaught, $exception, $payload) {
if (isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'Baiduspider') !== false) {
// ignore baidu spiderreturntrue;
}
// no other ignoresreturnfalse;
};
);
Rollbar::init($config);
code_version
The currently-deployed version of your code/application (e.g. a Git SHA). Should be a string.

Default: null

enable_utf8_sanitization
set to false, to disable running iconv on the payload, may be needed if there is invalid characters, and the payload is being destroyed

Default: true

environment
Environment name, e.g. `'production'` or `'development'`

Default: 'production'

error_sample_rates
Associative array mapping error numbers to sample rates. Sample rates are ratio out of 1, e.g. 0 is "never report", 1 is "always report", and 0.1 is "report 10% of the time". Sampling is done on a per-error basis.

Default: empty array, meaning all errors are reported.

handler
Either `'blocking'` or `'agent'`. `'blocking'` uses curl to send requests immediately; `'agent'` writes a relay log to be consumed by [rollbar-agent](https://github.com/rollbar/rollbar-agent).

Default: 'blocking'

host
Server hostname.

Default: null, which will result in a call to gethostname() (or php_uname('n') if that function does not exist)

include_error_code_context
A boolean that indicates you wish to gather code context for instances of PHP Errors. This can take a while because it requires reading the file from disk, so it's off by default.

Default: false

include_exception_code_context
A boolean that indicates you wish to gather code context for instances of PHP Exceptions. This can take a while because it requires reading the file from disk, so it's off by default.

Default: false

included_errno
A bitmask that includes all of the error levels to report. E.g. (E_ERROR \| E_WARNING) to only report E_ERROR and E_WARNING errors. This will be used in combination with `error_reporting()` to prevent reporting of errors if `use_error_reporting` is set to `true`.

Default: (E_ERROR | E_WARNING | E_PARSE | E_CORE_ERROR | E_USER_ERROR | E_RECOVERABLE_ERROR)

logger
An object that has a `log($level, $message)` method. If provided, will be used by RollbarNotifier to log messages.
person
An associative array containing data about the currently-logged in user. Required: `id`, optional: `username`, `email`. All values are strings.
person_fn
A function reference (string, etc. - anything that [call_user_func()](http://php.net/call_user_func) can handle) returning an array like the one for 'person'.
root
Path to your project's root dir
scrub_fields
Array of field names to scrub out of \_POST and \_SESSION. Values will be replaced with asterisks. If overriding, make sure to list all fields you want to scrub, not just fields you want to add to the default. Param names are converted to lowercase before comparing against the scrub list.

Default: ('passwd', 'password', 'secret', 'confirm_password', 'password_confirmation', 'auth_token', 'csrf_token')

shift_function
Whether to shift function names in stack traces down one frame, so that the function name correctly reflects the context of each frame.

Default: true

timeout
Request timeout for posting to rollbar, in seconds.

Default: 3

report_suppressed
Sets whether errors suppressed with '@' should be reported or not

Default: false

use_error_reporting
Sets whether to respect current `error_reporting()` level or not

Default: false

proxy
Send data via a proxy server.

E.g. Using a local proxy with no authentication

<?php$config['proxy'] = "127.0.0.1:8080";
?>

E.g. Using a local proxy with basic authentication

<?php$config['proxy'] = array(
'address' => '127.0.0.1:8080',
'username' => 'my_user',
'password' => 'my_password'
);
?>

Default: No proxy

Example use of error_sample_rates:

<?php$config['error_sample_rates'] = array(
// E_WARNING omitted, so defaults to 1E_NOTICE => 0.1,
E_USER_ERROR => 0.5,
// E_USER_WARNING will take the same value, 0.5E_USER_NOTICE => 0.1,
// E_STRICT and beyond will all be 0.1
);
?>

Example use of person_fn:

<?phpfunctionget_current_user() {
if ($_SESSION['user_id']) {
returnarray(
'id' => $_SESSION['user_id'], // required - value is a string'username' => $_SESSION['username'], // optional - value is a string'email' => $_SESSION['user_email'] // optional - value is a string
);
}
returnnull;
}
$config['person_fn'] = 'get_current_user';
?>

Related projects

A Laravel-specific package is available for integrating with Laravel: Laravel-Rollbar

A CakePHP-specific package is avaliable for integrating with CakePHP 2.x: CakeRollbar

A Flow-specific package is available for integrating with Neos Flow: m12/flow-rollbar

Help / Support

If you run into any issues, please email us at support@rollbar.com

You can also find us in IRC: #rollbar on chat.freenode.net

For bug reports, please open an issue on GitHub.

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Added some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

Testing

Tests are in tests. To run the tests: composer test To fix code style issues: composer fix

About

Error tracking and logging from PHP to Rollbar

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
This repository was archived by the owner on Mar 23, 2021. It is now read-only.

Repository files navigation

Rollbar notifier for PHP Build Status

This library detects errors and exceptions in your application and reports them to Rollbar for alerts, reporting, and analysis.

Supported PHP versions: 5.3, 5.4, 5.5, 5.6, 7, and HHVM (currently tested on 3.6.6).

Quick start

<?phpuse \Rollbar\Rollbar;
use \Rollbar\Payload\Level;
// installs global error and exception handlers
Rollbar::init(
array(
'access_token' => ROLLBAR_TEST_TOKEN,
'environment' => 'production'
)
);
try {
thrownew \Exception('test exception');
} catch (\Exception$e) {
Rollbar::log(Level::error(), $e);
}
// Message at level 'info'
Rollbar::log(Level::info(), 'testing info level');
// With extra data (3rd arg) and custom payload options (4th arg)
Rollbar::log(
Level::info(),
'testing extra data',
array("some_key" => "some value") // key-value additional data
);
// If you want to check if logging with Rollbar was successful$response = Rollbar::log(Level::info(), 'testing wasSuccessful()');
if (!$response->wasSuccessful()) {
thrownew \Exception('logging with Rollbar failed');
}
// raises an E_NOTICE which will *not* be reported by the error handler$foo = $bar;
// will be reported by the exception handlerthrownew \Exception('testing exception handler');
?>

Installation

Using Composer (recommended)

Add rollbar/rollbar to your composer.json:

{
"require": {
"rollbar/rollbar": "~1.0.1"
}
}

Manual installation if you are not using composer.json for your project

Keep in mind, that even if you're not using composer for your project (using composer.json), you will still need composer package to install rollbar-php dependencies.

  1. If you don't have composer yet, follow these instructions to get the package: install composer. It will be needed to install dependencies.
  2. Clone git repository rollbar/rollbar-php into a your external libraries path: git clone https://github.com/rollbar/rollbar-php
  3. Install rollbar-php dependencies: cd rollbar-php && composer install && cd ..
  4. Require rollbar-php in your PHP scripts: require_once YOUR_LIBS_PATH . '/rollbar-php/vendor/autoload.php';

Setup

Add the following code at your application's entry point:

<?phpuse \Rollbar\Rollbar;
$config = array(
// required'access_token' => 'POST_SERVER_ITEM_ACCESS_TOKEN',
// optional - environment name. any string will do.'environment' => 'production',
// optional - path to directory your code is in. used for linking stack traces.'root' => '/Users/brian/www/myapp'
);
Rollbar::init($config);
?>

Be sure to replace POST_SERVER_ITEM_ACCESS_TOKEN with your project's post_server_item access token, which you can find in the Rollbar.com interface.

This will install an exception handler (with set_exception_handler) and an error handler (with set_error_handler). If you'd rather not do that:

<?php$set_exception_handler = false;
$set_error_handler = false;
Rollbar::init($config, $set_exception_handler, $set_error_handler);
?>

For Heroku Users

First, add the addon:

heroku addons:create rollbar:free

The access_token and root config variables will be automatically detected, so the config is simply:

<?phpuseRollbar\Rollbar;
Rollbar::init(array(
'environment' => 'production'
));
?>

Basic Usage

That's it! Uncaught errors and exceptions will now be reported to Rollbar.

If you'd like to report exceptions that you catch yourself:

<?phpuseRollbar\Rollbar;
useRollbar\Payload\Level;
try {
do_something();
} catch (\Exception$e) {
Rollbar::log(Level::error(), $e);
// or
Rollbar::log(Level::error(), $e, array("my" => "extra", "data" => 42));
}
?>

You can also send Rollbar log-like messages:

<?phpuseRollbar\Rollbar;
useRollbar\Payload\Level;
Rollbar::log(Level::warning(), 'could not connect to mysql server');
Rollbar::log(
Level::info(), 'Here is a message with some additional data',
array('x' => 10, 'code' => 'blue')
);
?>

Using Monolog

Here is an example of how to use Rollbar as a handler for Monolog:

useMonolog\Logger;
useRollbar\Rollbar;
useRollbar\Payload\Level;
$config = array('access_token' => 'POST_SERVER_ITEM_ACCESS_TOKEN');
// installs global error and exception handlers
Rollbar::init($config);
$log = newLogger('test');
$log->pushHandler(new \Monolog\Handler\PsrHandler(Rollbar::logger()));
try {
thrownew \Exception('exception for monolog');
} catch (\Exception$e) {
$log->error($e);
}

Configuration

Asynchronous Reporting

By default, payloads (batched or not) are sent as part of script execution. This is easy to configure but may negatively impact performance. With some additional setup, payloads can be written to a local relay file instead; that file will be consumed by rollbar-agent asynchronously. To turn this on, set the following config params:

<?php$config = array(
// ... rest of current config'handler' => 'agent',
'agent_log_location' => '/var/www'// not including final slash. must be writeable by the user php runs as.
);
?>

You'll also need to run the agent. See the rollbar-agent docs for setup instructions.

Configuration reference

All of the following options can be passed as keys in the $config array.

access_token
Your project access token.
agent_log_location
Path to the directory where agent relay log files should be written. Should not include final slash. Only used when handler is `agent`.

Default: /var/www

base_api_url
The base api url to post to.

Default: https://api.rollbar.com/api/1/

branch
Name of the current branch.

Default: master

capture_error_stacktraces
Record full stacktraces for PHP errors.

Default: true

checkIgnore
Function called before sending payload to Rollbar, return true to stop the error from being sent to Rollbar.

Default: null

Parameters:

  • $isUncaught: boolean value set to true if the error was an uncaught exception.
  • $exception: a RollbarException instance that will allow you to get the message or exception
  • $payload: an array containing the payload as it will be sent to Rollbar. Payload schema can be found at https://rollbar.com/docs/api/items_post/
$config = array(
'access_token' => '...',
'checkIgnore' => function ($isUncaught, $exception, $payload) {
if (isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'Baiduspider') !== false) {
// ignore baidu spiderreturntrue;
}
// no other ignoresreturnfalse;
};
);
Rollbar::init($config);
code_version
The currently-deployed version of your code/application (e.g. a Git SHA). Should be a string.

Default: null

enable_utf8_sanitization
set to false, to disable running iconv on the payload, may be needed if there is invalid characters, and the payload is being destroyed

Default: true

environment
Environment name, e.g. `'production'` or `'development'`

Default: 'production'

error_sample_rates
Associative array mapping error numbers to sample rates. Sample rates are ratio out of 1, e.g. 0 is "never report", 1 is "always report", and 0.1 is "report 10% of the time". Sampling is done on a per-error basis.

Default: empty array, meaning all errors are reported.

handler
Either `'blocking'` or `'agent'`. `'blocking'` uses curl to send requests immediately; `'agent'` writes a relay log to be consumed by [rollbar-agent](https://github.com/rollbar/rollbar-agent).

Default: 'blocking'

host
Server hostname.

Default: null, which will result in a call to gethostname() (or php_uname('n') if that function does not exist)

include_error_code_context
A boolean that indicates you wish to gather code context for instances of PHP Errors. This can take a while because it requires reading the file from disk, so it's off by default.

Default: false

include_exception_code_context
A boolean that indicates you wish to gather code context for instances of PHP Exceptions. This can take a while because it requires reading the file from disk, so it's off by default.

Default: false

included_errno
A bitmask that includes all of the error levels to report. E.g. (E_ERROR \| E_WARNING) to only report E_ERROR and E_WARNING errors. This will be used in combination with `error_reporting()` to prevent reporting of errors if `use_error_reporting` is set to `true`.

Default: (E_ERROR | E_WARNING | E_PARSE | E_CORE_ERROR | E_USER_ERROR | E_RECOVERABLE_ERROR)

logger
An object that has a `log($level, $message)` method. If provided, will be used by RollbarNotifier to log messages.
person
An associative array containing data about the currently-logged in user. Required: `id`, optional: `username`, `email`. All values are strings.
person_fn
A function reference (string, etc. - anything that [call_user_func()](http://php.net/call_user_func) can handle) returning an array like the one for 'person'.
root
Path to your project's root dir
scrub_fields
Array of field names to scrub out of \_POST and \_SESSION. Values will be replaced with asterisks. If overriding, make sure to list all fields you want to scrub, not just fields you want to add to the default. Param names are converted to lowercase before comparing against the scrub list.

Default: ('passwd', 'password', 'secret', 'confirm_password', 'password_confirmation', 'auth_token', 'csrf_token')

shift_function
Whether to shift function names in stack traces down one frame, so that the function name correctly reflects the context of each frame.

Default: true

timeout
Request timeout for posting to rollbar, in seconds.

Default: 3

report_suppressed
Sets whether errors suppressed with '@' should be reported or not

Default: false

use_error_reporting
Sets whether to respect current `error_reporting()` level or not

Default: false

proxy
Send data via a proxy server.

E.g. Using a local proxy with no authentication

<?php$config['proxy'] = "127.0.0.1:8080";
?>

E.g. Using a local proxy with basic authentication

<?php$config['proxy'] = array(
'address' => '127.0.0.1:8080',
'username' => 'my_user',
'password' => 'my_password'
);
?>

Default: No proxy

Example use of error_sample_rates:

<?php$config['error_sample_rates'] = array(
// E_WARNING omitted, so defaults to 1E_NOTICE => 0.1,
E_USER_ERROR => 0.5,
// E_USER_WARNING will take the same value, 0.5E_USER_NOTICE => 0.1,
// E_STRICT and beyond will all be 0.1
);
?>

Example use of person_fn:

<?phpfunctionget_current_user() {
if ($_SESSION['user_id']) {
returnarray(
'id' => $_SESSION['user_id'], // required - value is a string'username' => $_SESSION['username'], // optional - value is a string'email' => $_SESSION['user_email'] // optional - value is a string
);
}
returnnull;
}
$config['person_fn'] = 'get_current_user';
?>

Related projects

A Laravel-specific package is available for integrating with Laravel: Laravel-Rollbar

A CakePHP-specific package is avaliable for integrating with CakePHP 2.x: CakeRollbar

A Flow-specific package is available for integrating with Neos Flow: m12/flow-rollbar

Help / Support

If you run into any issues, please email us at support@rollbar.com

You can also find us in IRC: #rollbar on chat.freenode.net

For bug reports, please open an issue on GitHub.

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Added some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

Testing

Tests are in tests. To run the tests: composer test To fix code style issues: composer fix

About

Error tracking and logging from PHP to Rollbar

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
This repository was archived by the owner on Mar 23, 2021. It is now read-only.

Repository files navigation

Rollbar notifier for PHP Build Status

This library detects errors and exceptions in your application and reports them to Rollbar for alerts, reporting, and analysis.

Supported PHP versions: 5.3, 5.4, 5.5, 5.6, 7, and HHVM (currently tested on 3.6.6).

Quick start

<?phpuse \Rollbar\Rollbar;
use \Rollbar\Payload\Level;
// installs global error and exception handlers
Rollbar::init(
array(
'access_token' => ROLLBAR_TEST_TOKEN,
'environment' => 'production'
)
);
try {
thrownew \Exception('test exception');
} catch (\Exception$e) {
Rollbar::log(Level::error(), $e);
}
// Message at level 'info'
Rollbar::log(Level::info(), 'testing info level');
// With extra data (3rd arg) and custom payload options (4th arg)
Rollbar::log(
Level::info(),
'testing extra data',
array("some_key" => "some value") // key-value additional data
);
// If you want to check if logging with Rollbar was successful$response = Rollbar::log(Level::info(), 'testing wasSuccessful()');
if (!$response->wasSuccessful()) {
thrownew \Exception('logging with Rollbar failed');
}
// raises an E_NOTICE which will *not* be reported by the error handler$foo = $bar;
// will be reported by the exception handlerthrownew \Exception('testing exception handler');
?>

Installation

Using Composer (recommended)

Add rollbar/rollbar to your composer.json:

{
"require": {
"rollbar/rollbar": "~1.0.1"
}
}

Manual installation if you are not using composer.json for your project

Keep in mind, that even if you're not using composer for your project (using composer.json), you will still need composer package to install rollbar-php dependencies.

  1. If you don't have composer yet, follow these instructions to get the package: install composer. It will be needed to install dependencies.
  2. Clone git repository rollbar/rollbar-php into a your external libraries path: git clone https://github.com/rollbar/rollbar-php
  3. Install rollbar-php dependencies: cd rollbar-php && composer install && cd ..
  4. Require rollbar-php in your PHP scripts: require_once YOUR_LIBS_PATH . '/rollbar-php/vendor/autoload.php';

Setup

Add the following code at your application's entry point:

<?phpuse \Rollbar\Rollbar;
$config = array(
// required'access_token' => 'POST_SERVER_ITEM_ACCESS_TOKEN',
// optional - environment name. any string will do.'environment' => 'production',
// optional - path to directory your code is in. used for linking stack traces.'root' => '/Users/brian/www/myapp'
);
Rollbar::init($config);
?>

Be sure to replace POST_SERVER_ITEM_ACCESS_TOKEN with your project's post_server_item access token, which you can find in the Rollbar.com interface.

This will install an exception handler (with set_exception_handler) and an error handler (with set_error_handler). If you'd rather not do that:

<?php$set_exception_handler = false;
$set_error_handler = false;
Rollbar::init($config, $set_exception_handler, $set_error_handler);
?>

For Heroku Users

First, add the addon:

heroku addons:create rollbar:free

The access_token and root config variables will be automatically detected, so the config is simply:

<?phpuseRollbar\Rollbar;
Rollbar::init(array(
'environment' => 'production'
));
?>

Basic Usage

That's it! Uncaught errors and exceptions will now be reported to Rollbar.

If you'd like to report exceptions that you catch yourself:

<?phpuseRollbar\Rollbar;
useRollbar\Payload\Level;
try {
do_something();
} catch (\Exception$e) {
Rollbar::log(Level::error(), $e);
// or
Rollbar::log(Level::error(), $e, array("my" => "extra", "data" => 42));
}
?>

You can also send Rollbar log-like messages:

<?phpuseRollbar\Rollbar;
useRollbar\Payload\Level;
Rollbar::log(Level::warning(), 'could not connect to mysql server');
Rollbar::log(
Level::info(), 'Here is a message with some additional data',
array('x' => 10, 'code' => 'blue')
);
?>

Using Monolog

Here is an example of how to use Rollbar as a handler for Monolog:

useMonolog\Logger;
useRollbar\Rollbar;
useRollbar\Payload\Level;
$config = array('access_token' => 'POST_SERVER_ITEM_ACCESS_TOKEN');
// installs global error and exception handlers
Rollbar::init($config);
$log = newLogger('test');
$log->pushHandler(new \Monolog\Handler\PsrHandler(Rollbar::logger()));
try {
thrownew \Exception('exception for monolog');
} catch (\Exception$e) {
$log->error($e);
}

Configuration

Asynchronous Reporting

By default, payloads (batched or not) are sent as part of script execution. This is easy to configure but may negatively impact performance. With some additional setup, payloads can be written to a local relay file instead; that file will be consumed by rollbar-agent asynchronously. To turn this on, set the following config params:

<?php$config = array(
// ... rest of current config'handler' => 'agent',
'agent_log_location' => '/var/www'// not including final slash. must be writeable by the user php runs as.
);
?>

You'll also need to run the agent. See the rollbar-agent docs for setup instructions.

Configuration reference

All of the following options can be passed as keys in the $config array.

access_token
Your project access token.
agent_log_location
Path to the directory where agent relay log files should be written. Should not include final slash. Only used when handler is `agent`.

Default: /var/www

base_api_url
The base api url to post to.

Default: https://api.rollbar.com/api/1/

branch
Name of the current branch.

Default: master

capture_error_stacktraces
Record full stacktraces for PHP errors.

Default: true

checkIgnore
Function called before sending payload to Rollbar, return true to stop the error from being sent to Rollbar.

Default: null

Parameters:

  • $isUncaught: boolean value set to true if the error was an uncaught exception.
  • $exception: a RollbarException instance that will allow you to get the message or exception
  • $payload: an array containing the payload as it will be sent to Rollbar. Payload schema can be found at https://rollbar.com/docs/api/items_post/
$config = array(
'access_token' => '...',
'checkIgnore' => function ($isUncaught, $exception, $payload) {
if (isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'Baiduspider') !== false) {
// ignore baidu spiderreturntrue;
}
// no other ignoresreturnfalse;
};
);
Rollbar::init($config);
code_version
The currently-deployed version of your code/application (e.g. a Git SHA). Should be a string.

Default: null

enable_utf8_sanitization
set to false, to disable running iconv on the payload, may be needed if there is invalid characters, and the payload is being destroyed

Default: true

environment
Environment name, e.g. `'production'` or `'development'`

Default: 'production'

error_sample_rates
Associative array mapping error numbers to sample rates. Sample rates are ratio out of 1, e.g. 0 is "never report", 1 is "always report", and 0.1 is "report 10% of the time". Sampling is done on a per-error basis.

Default: empty array, meaning all errors are reported.

handler
Either `'blocking'` or `'agent'`. `'blocking'` uses curl to send requests immediately; `'agent'` writes a relay log to be consumed by [rollbar-agent](https://github.com/rollbar/rollbar-agent).

Default: 'blocking'

host
Server hostname.

Default: null, which will result in a call to gethostname() (or php_uname('n') if that function does not exist)

include_error_code_context
A boolean that indicates you wish to gather code context for instances of PHP Errors. This can take a while because it requires reading the file from disk, so it's off by default.

Default: false

include_exception_code_context
A boolean that indicates you wish to gather code context for instances of PHP Exceptions. This can take a while because it requires reading the file from disk, so it's off by default.

Default: false

included_errno
A bitmask that includes all of the error levels to report. E.g. (E_ERROR \| E_WARNING) to only report E_ERROR and E_WARNING errors. This will be used in combination with `error_reporting()` to prevent reporting of errors if `use_error_reporting` is set to `true`.

Default: (E_ERROR | E_WARNING | E_PARSE | E_CORE_ERROR | E_USER_ERROR | E_RECOVERABLE_ERROR)

logger
An object that has a `log($level, $message)` method. If provided, will be used by RollbarNotifier to log messages.
person
An associative array containing data about the currently-logged in user. Required: `id`, optional: `username`, `email`. All values are strings.
person_fn
A function reference (string, etc. - anything that [call_user_func()](http://php.net/call_user_func) can handle) returning an array like the one for 'person'.
root
Path to your project's root dir
scrub_fields
Array of field names to scrub out of \_POST and \_SESSION. Values will be replaced with asterisks. If overriding, make sure to list all fields you want to scrub, not just fields you want to add to the default. Param names are converted to lowercase before comparing against the scrub list.

Default: ('passwd', 'password', 'secret', 'confirm_password', 'password_confirmation', 'auth_token', 'csrf_token')

shift_function
Whether to shift function names in stack traces down one frame, so that the function name correctly reflects the context of each frame.

Default: true

timeout
Request timeout for posting to rollbar, in seconds.

Default: 3

report_suppressed
Sets whether errors suppressed with '@' should be reported or not

Default: false

use_error_reporting
Sets whether to respect current `error_reporting()` level or not

Default: false

proxy
Send data via a proxy server.

E.g. Using a local proxy with no authentication

<?php$config['proxy'] = "127.0.0.1:8080";
?>

E.g. Using a local proxy with basic authentication

<?php$config['proxy'] = array(
'address' => '127.0.0.1:8080',
'username' => 'my_user',
'password' => 'my_password'
);
?>

Default: No proxy

Example use of error_sample_rates:

<?php$config['error_sample_rates'] = array(
// E_WARNING omitted, so defaults to 1E_NOTICE => 0.1,
E_USER_ERROR => 0.5,
// E_USER_WARNING will take the same value, 0.5E_USER_NOTICE => 0.1,
// E_STRICT and beyond will all be 0.1
);
?>

Example use of person_fn:

<?phpfunctionget_current_user() {
if ($_SESSION['user_id']) {
returnarray(
'id' => $_SESSION['user_id'], // required - value is a string'username' => $_SESSION['username'], // optional - value is a string'email' => $_SESSION['user_email'] // optional - value is a string
);
}
returnnull;
}
$config['person_fn'] = 'get_current_user';
?>

Related projects

A Laravel-specific package is available for integrating with Laravel: Laravel-Rollbar

A CakePHP-specific package is avaliable for integrating with CakePHP 2.x: CakeRollbar

A Flow-specific package is available for integrating with Neos Flow: m12/flow-rollbar

Help / Support

If you run into any issues, please email us at support@rollbar.com

You can also find us in IRC: #rollbar on chat.freenode.net

For bug reports, please open an issue on GitHub.

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Added some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

Testing

Tests are in tests. To run the tests: composer test To fix code style issues: composer fix

About

Error tracking and logging from PHP to Rollbar

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
This repository was archived by the owner on Mar 23, 2021. It is now read-only.

Repository files navigation

Rollbar notifier for PHP Build Status

This library detects errors and exceptions in your application and reports them to Rollbar for alerts, reporting, and analysis.

Supported PHP versions: 5.3, 5.4, 5.5, 5.6, 7, and HHVM (currently tested on 3.6.6).

Quick start

<?phpuse \Rollbar\Rollbar;
use \Rollbar\Payload\Level;
// installs global error and exception handlers
Rollbar::init(
array(
'access_token' => ROLLBAR_TEST_TOKEN,
'environment' => 'production'
)
);
try {
thrownew \Exception('test exception');
} catch (\Exception$e) {
Rollbar::log(Level::error(), $e);
}
// Message at level 'info'
Rollbar::log(Level::info(), 'testing info level');
// With extra data (3rd arg) and custom payload options (4th arg)
Rollbar::log(
Level::info(),
'testing extra data',
array("some_key" => "some value") // key-value additional data
);
// If you want to check if logging with Rollbar was successful$response = Rollbar::log(Level::info(), 'testing wasSuccessful()');
if (!$response->wasSuccessful()) {
thrownew \Exception('logging with Rollbar failed');
}
// raises an E_NOTICE which will *not* be reported by the error handler$foo = $bar;
// will be reported by the exception handlerthrownew \Exception('testing exception handler');
?>

Installation

Using Composer (recommended)

Add rollbar/rollbar to your composer.json:

{
"require": {
"rollbar/rollbar": "~1.0.1"
}
}

Manual installation if you are not using composer.json for your project

Keep in mind, that even if you're not using composer for your project (using composer.json), you will still need composer package to install rollbar-php dependencies.

  1. If you don't have composer yet, follow these instructions to get the package: install composer. It will be needed to install dependencies.
  2. Clone git repository rollbar/rollbar-php into a your external libraries path: git clone https://github.com/rollbar/rollbar-php
  3. Install rollbar-php dependencies: cd rollbar-php && composer install && cd ..
  4. Require rollbar-php in your PHP scripts: require_once YOUR_LIBS_PATH . '/rollbar-php/vendor/autoload.php';

Setup

Add the following code at your application's entry point:

<?phpuse \Rollbar\Rollbar;
$config = array(
// required'access_token' => 'POST_SERVER_ITEM_ACCESS_TOKEN',
// optional - environment name. any string will do.'environment' => 'production',
// optional - path to directory your code is in. used for linking stack traces.'root' => '/Users/brian/www/myapp'
);
Rollbar::init($config);
?>

Be sure to replace POST_SERVER_ITEM_ACCESS_TOKEN with your project's post_server_item access token, which you can find in the Rollbar.com interface.

This will install an exception handler (with set_exception_handler) and an error handler (with set_error_handler). If you'd rather not do that:

<?php$set_exception_handler = false;
$set_error_handler = false;
Rollbar::init($config, $set_exception_handler, $set_error_handler);
?>

For Heroku Users

First, add the addon:

heroku addons:create rollbar:free

The access_token and root config variables will be automatically detected, so the config is simply:

<?phpuseRollbar\Rollbar;
Rollbar::init(array(
'environment' => 'production'
));
?>

Basic Usage

That's it! Uncaught errors and exceptions will now be reported to Rollbar.

If you'd like to report exceptions that you catch yourself:

<?phpuseRollbar\Rollbar;
useRollbar\Payload\Level;
try {
do_something();
} catch (\Exception$e) {
Rollbar::log(Level::error(), $e);
// or
Rollbar::log(Level::error(), $e, array("my" => "extra", "data" => 42));
}
?>

You can also send Rollbar log-like messages:

<?phpuseRollbar\Rollbar;
useRollbar\Payload\Level;
Rollbar::log(Level::warning(), 'could not connect to mysql server');
Rollbar::log(
Level::info(), 'Here is a message with some additional data',
array('x' => 10, 'code' => 'blue')
);
?>

Using Monolog

Here is an example of how to use Rollbar as a handler for Monolog:

useMonolog\Logger;
useRollbar\Rollbar;
useRollbar\Payload\Level;
$config = array('access_token' => 'POST_SERVER_ITEM_ACCESS_TOKEN');
// installs global error and exception handlers
Rollbar::init($config);
$log = newLogger('test');
$log->pushHandler(new \Monolog\Handler\PsrHandler(Rollbar::logger()));
try {
thrownew \Exception('exception for monolog');
} catch (\Exception$e) {
$log->error($e);
}

Configuration

Asynchronous Reporting

By default, payloads (batched or not) are sent as part of script execution. This is easy to configure but may negatively impact performance. With some additional setup, payloads can be written to a local relay file instead; that file will be consumed by rollbar-agent asynchronously. To turn this on, set the following config params:

<?php$config = array(
// ... rest of current config'handler' => 'agent',
'agent_log_location' => '/var/www'// not including final slash. must be writeable by the user php runs as.
);
?>

You'll also need to run the agent. See the rollbar-agent docs for setup instructions.

Configuration reference

All of the following options can be passed as keys in the $config array.

access_token
Your project access token.
agent_log_location
Path to the directory where agent relay log files should be written. Should not include final slash. Only used when handler is `agent`.

Default: /var/www

base_api_url
The base api url to post to.

Default: https://api.rollbar.com/api/1/

branch
Name of the current branch.

Default: master

capture_error_stacktraces
Record full stacktraces for PHP errors.

Default: true

checkIgnore
Function called before sending payload to Rollbar, return true to stop the error from being sent to Rollbar.

Default: null

Parameters:

  • $isUncaught: boolean value set to true if the error was an uncaught exception.
  • $exception: a RollbarException instance that will allow you to get the message or exception
  • $payload: an array containing the payload as it will be sent to Rollbar. Payload schema can be found at https://rollbar.com/docs/api/items_post/
$config = array(
'access_token' => '...',
'checkIgnore' => function ($isUncaught, $exception, $payload) {
if (isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'Baiduspider') !== false) {
// ignore baidu spiderreturntrue;
}
// no other ignoresreturnfalse;
};
);
Rollbar::init($config);
code_version
The currently-deployed version of your code/application (e.g. a Git SHA). Should be a string.

Default: null

enable_utf8_sanitization
set to false, to disable running iconv on the payload, may be needed if there is invalid characters, and the payload is being destroyed

Default: true

environment
Environment name, e.g. `'production'` or `'development'`

Default: 'production'

error_sample_rates
Associative array mapping error numbers to sample rates. Sample rates are ratio out of 1, e.g. 0 is "never report", 1 is "always report", and 0.1 is "report 10% of the time". Sampling is done on a per-error basis.

Default: empty array, meaning all errors are reported.

handler
Either `'blocking'` or `'agent'`. `'blocking'` uses curl to send requests immediately; `'agent'` writes a relay log to be consumed by [rollbar-agent](https://github.com/rollbar/rollbar-agent).

Default: 'blocking'

host
Server hostname.

Default: null, which will result in a call to gethostname() (or php_uname('n') if that function does not exist)

include_error_code_context
A boolean that indicates you wish to gather code context for instances of PHP Errors. This can take a while because it requires reading the file from disk, so it's off by default.

Default: false

include_exception_code_context
A boolean that indicates you wish to gather code context for instances of PHP Exceptions. This can take a while because it requires reading the file from disk, so it's off by default.

Default: false

included_errno
A bitmask that includes all of the error levels to report. E.g. (E_ERROR \| E_WARNING) to only report E_ERROR and E_WARNING errors. This will be used in combination with `error_reporting()` to prevent reporting of errors if `use_error_reporting` is set to `true`.

Default: (E_ERROR | E_WARNING | E_PARSE | E_CORE_ERROR | E_USER_ERROR | E_RECOVERABLE_ERROR)

logger
An object that has a `log($level, $message)` method. If provided, will be used by RollbarNotifier to log messages.
person
An associative array containing data about the currently-logged in user. Required: `id`, optional: `username`, `email`. All values are strings.
person_fn
A function reference (string, etc. - anything that [call_user_func()](http://php.net/call_user_func) can handle) returning an array like the one for 'person'.
root
Path to your project's root dir
scrub_fields
Array of field names to scrub out of \_POST and \_SESSION. Values will be replaced with asterisks. If overriding, make sure to list all fields you want to scrub, not just fields you want to add to the default. Param names are converted to lowercase before comparing against the scrub list.

Default: ('passwd', 'password', 'secret', 'confirm_password', 'password_confirmation', 'auth_token', 'csrf_token')

shift_function
Whether to shift function names in stack traces down one frame, so that the function name correctly reflects the context of each frame.

Default: true

timeout
Request timeout for posting to rollbar, in seconds.

Default: 3

report_suppressed
Sets whether errors suppressed with '@' should be reported or not

Default: false

use_error_reporting
Sets whether to respect current `error_reporting()` level or not

Default: false

proxy
Send data via a proxy server.

E.g. Using a local proxy with no authentication

<?php$config['proxy'] = "127.0.0.1:8080";
?>

E.g. Using a local proxy with basic authentication

<?php$config['proxy'] = array(
'address' => '127.0.0.1:8080',
'username' => 'my_user',
'password' => 'my_password'
);
?>

Default: No proxy

Example use of error_sample_rates:

<?php$config['error_sample_rates'] = array(
// E_WARNING omitted, so defaults to 1E_NOTICE => 0.1,
E_USER_ERROR => 0.5,
// E_USER_WARNING will take the same value, 0.5E_USER_NOTICE => 0.1,
// E_STRICT and beyond will all be 0.1
);
?>

Example use of person_fn:

<?phpfunctionget_current_user() {
if ($_SESSION['user_id']) {
returnarray(
'id' => $_SESSION['user_id'], // required - value is a string'username' => $_SESSION['username'], // optional - value is a string'email' => $_SESSION['user_email'] // optional - value is a string
);
}
returnnull;
}
$config['person_fn'] = 'get_current_user';
?>

Related projects

A Laravel-specific package is available for integrating with Laravel: Laravel-Rollbar

A CakePHP-specific package is avaliable for integrating with CakePHP 2.x: CakeRollbar

A Flow-specific package is available for integrating with Neos Flow: m12/flow-rollbar

Help / Support

If you run into any issues, please email us at support@rollbar.com

You can also find us in IRC: #rollbar on chat.freenode.net

For bug reports, please open an issue on GitHub.

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Added some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

Testing

Tests are in tests. To run the tests: composer test To fix code style issues: composer fix

About

Error tracking and logging from PHP to Rollbar

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
This repository was archived by the owner on Mar 23, 2021. It is now read-only.

Repository files navigation

Rollbar notifier for PHP Build Status

This library detects errors and exceptions in your application and reports them to Rollbar for alerts, reporting, and analysis.

Supported PHP versions: 5.3, 5.4, 5.5, 5.6, 7, and HHVM (currently tested on 3.6.6).

Quick start

<?phpuse \Rollbar\Rollbar;
use \Rollbar\Payload\Level;
// installs global error and exception handlers
Rollbar::init(
array(
'access_token' => ROLLBAR_TEST_TOKEN,
'environment' => 'production'
)
);
try {
thrownew \Exception('test exception');
} catch (\Exception$e) {
Rollbar::log(Level::error(), $e);
}
// Message at level 'info'
Rollbar::log(Level::info(), 'testing info level');
// With extra data (3rd arg) and custom payload options (4th arg)
Rollbar::log(
Level::info(),
'testing extra data',
array("some_key" => "some value") // key-value additional data
);
// If you want to check if logging with Rollbar was successful$response = Rollbar::log(Level::info(), 'testing wasSuccessful()');
if (!$response->wasSuccessful()) {
thrownew \Exception('logging with Rollbar failed');
}
// raises an E_NOTICE which will *not* be reported by the error handler$foo = $bar;
// will be reported by the exception handlerthrownew \Exception('testing exception handler');
?>

Installation

Using Composer (recommended)

Add rollbar/rollbar to your composer.json:

{
"require": {
"rollbar/rollbar": "~1.0.1"
}
}

Manual installation if you are not using composer.json for your project

Keep in mind, that even if you're not using composer for your project (using composer.json), you will still need composer package to install rollbar-php dependencies.

  1. If you don't have composer yet, follow these instructions to get the package: install composer. It will be needed to install dependencies.
  2. Clone git repository rollbar/rollbar-php into a your external libraries path: git clone https://github.com/rollbar/rollbar-php
  3. Install rollbar-php dependencies: cd rollbar-php && composer install && cd ..
  4. Require rollbar-php in your PHP scripts: require_once YOUR_LIBS_PATH . '/rollbar-php/vendor/autoload.php';

Setup

Add the following code at your application's entry point:

<?phpuse \Rollbar\Rollbar;
$config = array(
// required'access_token' => 'POST_SERVER_ITEM_ACCESS_TOKEN',
// optional - environment name. any string will do.'environment' => 'production',
// optional - path to directory your code is in. used for linking stack traces.'root' => '/Users/brian/www/myapp'
);
Rollbar::init($config);
?>

Be sure to replace POST_SERVER_ITEM_ACCESS_TOKEN with your project's post_server_item access token, which you can find in the Rollbar.com interface.

This will install an exception handler (with set_exception_handler) and an error handler (with set_error_handler). If you'd rather not do that:

<?php$set_exception_handler = false;
$set_error_handler = false;
Rollbar::init($config, $set_exception_handler, $set_error_handler);
?>

For Heroku Users

First, add the addon:

heroku addons:create rollbar:free

The access_token and root config variables will be automatically detected, so the config is simply:

<?phpuseRollbar\Rollbar;
Rollbar::init(array(
'environment' => 'production'
));
?>

Basic Usage

That's it! Uncaught errors and exceptions will now be reported to Rollbar.

If you'd like to report exceptions that you catch yourself:

<?phpuseRollbar\Rollbar;
useRollbar\Payload\Level;
try {
do_something();
} catch (\Exception$e) {
Rollbar::log(Level::error(), $e);
// or
Rollbar::log(Level::error(), $e, array("my" => "extra", "data" => 42));
}
?>

You can also send Rollbar log-like messages:

<?phpuseRollbar\Rollbar;
useRollbar\Payload\Level;
Rollbar::log(Level::warning(), 'could not connect to mysql server');
Rollbar::log(
Level::info(), 'Here is a message with some additional data',
array('x' => 10, 'code' => 'blue')
);
?>

Using Monolog

Here is an example of how to use Rollbar as a handler for Monolog:

useMonolog\Logger;
useRollbar\Rollbar;
useRollbar\Payload\Level;
$config = array('access_token' => 'POST_SERVER_ITEM_ACCESS_TOKEN');
// installs global error and exception handlers
Rollbar::init($config);
$log = newLogger('test');
$log->pushHandler(new \Monolog\Handler\PsrHandler(Rollbar::logger()));
try {
thrownew \Exception('exception for monolog');
} catch (\Exception$e) {
$log->error($e);
}

Configuration

Asynchronous Reporting

By default, payloads (batched or not) are sent as part of script execution. This is easy to configure but may negatively impact performance. With some additional setup, payloads can be written to a local relay file instead; that file will be consumed by rollbar-agent asynchronously. To turn this on, set the following config params:

<?php$config = array(
// ... rest of current config'handler' => 'agent',
'agent_log_location' => '/var/www'// not including final slash. must be writeable by the user php runs as.
);
?>

You'll also need to run the agent. See the rollbar-agent docs for setup instructions.

Configuration reference

All of the following options can be passed as keys in the $config array.

access_token
Your project access token.
agent_log_location
Path to the directory where agent relay log files should be written. Should not include final slash. Only used when handler is `agent`.

Default: /var/www

base_api_url
The base api url to post to.

Default: https://api.rollbar.com/api/1/

branch
Name of the current branch.

Default: master

capture_error_stacktraces
Record full stacktraces for PHP errors.

Default: true

checkIgnore
Function called before sending payload to Rollbar, return true to stop the error from being sent to Rollbar.

Default: null

Parameters:

  • $isUncaught: boolean value set to true if the error was an uncaught exception.
  • $exception: a RollbarException instance that will allow you to get the message or exception
  • $payload: an array containing the payload as it will be sent to Rollbar. Payload schema can be found at https://rollbar.com/docs/api/items_post/
$config = array(
'access_token' => '...',
'checkIgnore' => function ($isUncaught, $exception, $payload) {
if (isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'Baiduspider') !== false) {
// ignore baidu spiderreturntrue;
}
// no other ignoresreturnfalse;
};
);
Rollbar::init($config);
code_version
The currently-deployed version of your code/application (e.g. a Git SHA). Should be a string.

Default: null

enable_utf8_sanitization
set to false, to disable running iconv on the payload, may be needed if there is invalid characters, and the payload is being destroyed

Default: true

environment
Environment name, e.g. `'production'` or `'development'`

Default: 'production'

error_sample_rates
Associative array mapping error numbers to sample rates. Sample rates are ratio out of 1, e.g. 0 is "never report", 1 is "always report", and 0.1 is "report 10% of the time". Sampling is done on a per-error basis.

Default: empty array, meaning all errors are reported.

handler
Either `'blocking'` or `'agent'`. `'blocking'` uses curl to send requests immediately; `'agent'` writes a relay log to be consumed by [rollbar-agent](https://github.com/rollbar/rollbar-agent).

Default: 'blocking'

host
Server hostname.

Default: null, which will result in a call to gethostname() (or php_uname('n') if that function does not exist)

include_error_code_context
A boolean that indicates you wish to gather code context for instances of PHP Errors. This can take a while because it requires reading the file from disk, so it's off by default.

Default: false

include_exception_code_context
A boolean that indicates you wish to gather code context for instances of PHP Exceptions. This can take a while because it requires reading the file from disk, so it's off by default.

Default: false

included_errno
A bitmask that includes all of the error levels to report. E.g. (E_ERROR \| E_WARNING) to only report E_ERROR and E_WARNING errors. This will be used in combination with `error_reporting()` to prevent reporting of errors if `use_error_reporting` is set to `true`.

Default: (E_ERROR | E_WARNING | E_PARSE | E_CORE_ERROR | E_USER_ERROR | E_RECOVERABLE_ERROR)

logger
An object that has a `log($level, $message)` method. If provided, will be used by RollbarNotifier to log messages.
person
An associative array containing data about the currently-logged in user. Required: `id`, optional: `username`, `email`. All values are strings.
person_fn
A function reference (string, etc. - anything that [call_user_func()](http://php.net/call_user_func) can handle) returning an array like the one for 'person'.
root
Path to your project's root dir
scrub_fields
Array of field names to scrub out of \_POST and \_SESSION. Values will be replaced with asterisks. If overriding, make sure to list all fields you want to scrub, not just fields you want to add to the default. Param names are converted to lowercase before comparing against the scrub list.

Default: ('passwd', 'password', 'secret', 'confirm_password', 'password_confirmation', 'auth_token', 'csrf_token')

shift_function
Whether to shift function names in stack traces down one frame, so that the function name correctly reflects the context of each frame.

Default: true

timeout
Request timeout for posting to rollbar, in seconds.

Default: 3

report_suppressed
Sets whether errors suppressed with '@' should be reported or not

Default: false

use_error_reporting
Sets whether to respect current `error_reporting()` level or not

Default: false

proxy
Send data via a proxy server.

E.g. Using a local proxy with no authentication

<?php$config['proxy'] = "127.0.0.1:8080";
?>

E.g. Using a local proxy with basic authentication

<?php$config['proxy'] = array(
'address' => '127.0.0.1:8080',
'username' => 'my_user',
'password' => 'my_password'
);
?>

Default: No proxy

Example use of error_sample_rates:

<?php$config['error_sample_rates'] = array(
// E_WARNING omitted, so defaults to 1E_NOTICE => 0.1,
E_USER_ERROR => 0.5,
// E_USER_WARNING will take the same value, 0.5E_USER_NOTICE => 0.1,
// E_STRICT and beyond will all be 0.1
);
?>

Example use of person_fn:

<?phpfunctionget_current_user() {
if ($_SESSION['user_id']) {
returnarray(
'id' => $_SESSION['user_id'], // required - value is a string'username' => $_SESSION['username'], // optional - value is a string'email' => $_SESSION['user_email'] // optional - value is a string
);
}
returnnull;
}
$config['person_fn'] = 'get_current_user';
?>

Related projects

A Laravel-specific package is available for integrating with Laravel: Laravel-Rollbar

A CakePHP-specific package is avaliable for integrating with CakePHP 2.x: CakeRollbar

A Flow-specific package is available for integrating with Neos Flow: m12/flow-rollbar

Help / Support

If you run into any issues, please email us at support@rollbar.com

You can also find us in IRC: #rollbar on chat.freenode.net

For bug reports, please open an issue on GitHub.

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Added some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

Testing

Tests are in tests. To run the tests: composer test To fix code style issues: composer fix

About

Error tracking and logging from PHP to Rollbar

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages