talentrydev/rollbar

监视错误和异常并将它们报告给Rollbar

0.18.2 2021-12-07 15:24 UTC

This package is auto-updated.

Last update: 2024-09-07 21:28:21 UTC


README

PHP的Rollbar通知器 构建状态

这个库可以检测您的应用程序中的错误和异常,并将它们报告给 Rollbar 以进行警报、报告和分析。

## 目录

快速开始

<?php
// installs global error and exception handlers
Rollbar::init(array('access_token' => 'POST_SERVER_ITEM_ACCESS_TOKEN'));

try {
    throw new Exception('test exception');
} catch (Exception $e) {
    Rollbar::report_exception($e);
}

// Message at level 'info'
Rollbar::report_message('testing 123', Level::INFO);

// With extra data (3rd arg) and custom payload options (4th arg)
Rollbar::report_message('testing 123', Level::INFO,
                        // key-value additional data
                        array("some_key" => "some value"),  
                        // payload options (overrides defaults) - see api docs
                        array("fingerprint" => "custom-fingerprint-here"));

// raises an E_NOTICE which will *not* be reported by the error handler
$foo = $bar;

// will be reported by the exception handler
throw new Exception('test 2');
?>

安装

通用

下载 rollbar.phpLevel.php 并将它们放在您可以访问的地方。

如果使用Composer

rollbar/rollbar 添加到您的 composer.json

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

设置

在应用程序的入口点添加以下代码

<?php
require_once 'rollbar.php';

$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);
?>

请确保将 POST_SERVER_ITEM_ACCESS_TOKEN 替换为您的项目的 post_server_item 访问令牌,您可以在Rollbar.com界面中找到。

这将安装一个异常处理程序(使用 set_exception_handler)和一个错误处理程序(使用 set_error_handler)。如果您不想这样做

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

Heroku用户

首先,添加插件

heroku addons:create rollbar:free

配置变量 access_tokenroot 将自动检测,因此配置很简单

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

基本用法

就这样!未捕获的错误和异常现在将报告给Rollbar。

如果您想报告您自己捕获的异常

<?php
try {
    do_something();
} catch (Exception $e) {
    Rollbar::report_exception($e);
    // or
    Rollbar::report_exception($e, array("my" => "extra", "data" => 42));
}
?>

您还可以发送类似Rollbar日志的消息

<?php
Rollbar::report_message('could not connect to mysql server', Level::WARNING);
Rollbar::report_message('Here is a message with some additional data',
    Level::INFO, array('x' => 10, 'code' => 'blue'));
?>

批量处理

默认情况下,负载将在每次脚本执行结束时通过关闭处理程序发送到Rollbar服务器,或者当批量大小达到50时,以先到者为准。这对于标准短生命周期的脚本,如处理Web请求,非常有效。

如果您在长运行脚本中使用Rollbar,例如Laravel项目或后台工作程序,您可能希望手动刷新批处理。要刷新,请简单调用

Rollbar::flush();

例如,如果您使用Laravel,请将上述行添加到您的 App::after() 事件处理程序。或者在循环后台工作程序中,在每个循环结束时调用它。

您还可以调整最大批量大小或完全禁用批量处理。请参阅下面的 batch_sizebatched 配置变量。

使用Monolog

以下是如何将Rollbar用作Monolog处理程序的示例

use Monolog\Logger;
use Monolog\Handler\RollbarHandler;

$config = array('access_token' => 'POST_SERVER_ITEM_ACCESS_TOKEN');

// installs global error and exception handlers
Rollbar::init($config);

$log = new Logger('test');
$log->pushHandler(new RollbarHandler(Rollbar::$instance));

try {
    throw new Exception('exception for monolog');
} catch (Exception $e) {
    $log->error($e);
}

配置

异步报告

默认情况下,负载(批量或非批量)作为脚本执行的一部分发送。这很容易配置,但可能会对性能产生负面影响。通过一些额外的设置,负载可以写入本地中继文件,该文件将由 rollbar-agent 异步消费。要启用此功能,请设置以下配置参数

<?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.
);
?>

您还需要运行代理。请参阅 rollbar-agent 文档 了解设置说明。

配置参考

以下所有选项都可以作为 $config 数组的键传递。

access_token
您的项目访问令牌。
agent_log_location
应该写入代理中继日志文件的目录路径。不应包含最后的反斜杠。仅在处理器为 `agent` 时使用。

默认值:/var/www

base_api_url
要发送到的基础 API URL。

默认值:https://api.rollbar.com/api/1/

batch_size
如果达到这个大小,则提前刷新批次。

默认值:50

batched
设置为 True 以将单个请求的所有报告一起批处理。

默认值:true

branch
当前分支的名称。

默认值:master

capture_error_stacktraces
记录 PHP 错误的完整堆栈跟踪。

默认值:true

checkIgnore
在将有效载荷发送到 Rollbar 之前调用的函数,返回 true 以阻止错误发送到 Rollbar。

默认值:null
参数

  • $isUncaught: 如果错误是一个未捕获的异常,则设置为 true 的布尔值。
  • $exception: 一个允许您获取消息或异常的 RollbarException 实例
  • $payload: 包含将发送到 Rollbar 的有效载荷的数组。有效载荷模式可以在 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) { // 忽略百度蜘蛛 return true; }}
    // no other ignores
    return false;
}; 

); Rollbar::init($config);

  </dd>

  <dt>code_version</dt>
  <dd>The currently-deployed version of your code/application (e.g. a Git SHA). Should be a string.

Default: `null`
  </dd>
  
  <dt>enable_utf8_sanizations</dt>
  <dd>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`
  </dd>

  <dt>environment</dt>
  <dd>Environment name, e.g. `'production'` or `'development'`

Default: `'production'`
  </dd>

  <dt>error_sample_rates</dt>
  <dd>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.
  </dd>

  <dt>handler</dt>
  <dd>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'`
  </dd>

  <dt>host</dt>
  <dd>Server hostname.

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

  <dt>include_error_code_context</dt>
  <dd>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
  </dd>

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

Default: false
  </dd>

  <dt>included_errno</dt>
  <dd>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)
  </dd>

  <dt>logger</dt>
  <dd>An object that has a `log($level, $message)` method. If provided, will be used by RollbarNotifier to log messages.
  </dd>

  <dt>person</dt>
  <dd>An associative array containing data about the currently-logged in user. Required: `id`, optional: `username`, `email`. All values are strings.
  </dd>

  <dt>person_fn</dt>
  <dd>A function reference (string, etc. - anything that [call_user_func()](https://php.ac.cn/call_user_func) can handle) returning an array like the one for 'person'.
  </dd>

  <dt>root</dt>
  <dd>Path to your project's root dir
  </dd>

  <dt>scrub_fields</dt>
  <dd>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')`
  </dd>

  <dt>shift_function</dt>
  <dd>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`
  </dd>

  <dt>timeout</dt>
  <dd>Request timeout for posting to rollbar, in seconds.

Default: `3`
  </dd>

  <dt>report_suppressed</dt>
  <dd>Sets whether errors suppressed with '@' should be reported or not

Default: `false`
  </dd>

  <dt>use_error_reporting</dt>
  <dd>Sets whether to respect current `error_reporting()` level or not

Default: `false`
  </dd>

  <dt>proxy</dt>
  <dd>Send data via a proxy server.

E.g. Using a local proxy with no authentication

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

例如:使用带基本身份验证的本地代理

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

默认值:无代理

error_sample_rates 的示例用法

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

person_fn 的示例用法

<?php
function get_current_user() {
    if ($_SESSION['user_id']) {
        return array(
            '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
        );
    }
    return null;
}
$config['person_fn'] = 'get_current_user';
?>

相关项目

有可用于与 Laravel 集成的 Laravel 特定包:Laravel-Rollbar

有可用于与 CakePHP 2.x 集成的 CakePHP 特定包:CakeRollbar

帮助/支持

如果您遇到任何问题,请通过电子邮件发送给我们:support@rollbar.com

您也可以在 IRC 上找到我们:chat.freenode.net 上的 #rollbar

对于错误报告,请 在 GitHub 上打开一个问题

贡献

  1. 进行分叉
  2. 创建您的功能分支(git checkout -b my-new-feature
  3. 提交您的更改(git commit -am '添加一些功能'
  4. 推送到分支(git push origin my-new-feature
  5. 创建新的拉取请求

测试在 tests 中。要运行测试:phpunit