定制 laykou/rollbar-php 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

laykou/rollbar-php

最新稳定版本:v0.9.91

Composer 安装命令:

composer require laykou/rollbar-php

包简介

Monitors errors and exceptions and reports them to Rollbar. Allows Proxy authentication.

README 文档

README

PHP notifier for Rollbar. Catches and reports exceptions to Rollbar.com for alerts, reporting, and analysis.

Proxy authentication

The difference between the original Rollbar PHP plugin is that this allows also proxy authentication. You can configure it like this:

// With authentication
$config = [
  'proxy' => [
    'address' => '123.123.123.123:9876',
    'username' => 'my_name',
    'password' => 'my_password'
  ]
];

// Or you can use only the address:
$config = [
  'proxy' => '123.123.123.123:9876'
];

Rollbar::init($config);

Quick start

<?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', 'info');

// With extra data (3rd arg) and custom payload options (4th arg)
Rollbar::report_message('testing 123', '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');
?>

Installation

General

Download rollbar.php and put it somewhere you can access.

If Using Composer

Add Laykou/rollbar-php to your composer.json:

{
    "require": {
        "Laykou/rollbar-php": "*"
    }
}

Setup

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

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

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:add rollbar:free

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

<?php
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:

<?php
try {
    do_something();
} catch (Exception $e) {
    Rollbar::report_exception($e);
}
?>

You can also send Rollbar log-like messages:

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

Batching

By default, payloads are batched and sent to the Rollbar servers at the end of every script execution via a shutdown handler, or when the batch size reaches 50, whichever comes first. This works well in standard short-lived scripts, like serving web requests.

If you're using Rollbar in a long-running script, such as a Laravel project or a background worker, you may want to manually flush the batch. To flush, simply call:

Rollbar::flush();

For example, if using Laravel, add the above line to your App::after() event handler. Or in a looping background worker, call it at the end of each loop.

You can also tune the max batch size or disable batching altogether. See the batch_size and batched config variables, documented below.

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/

batch_size
Flush batch early if it reaches this size.

Default: 50

batched
True to batch all reports from a single request together.

Default: true

branch
Name of the current branch.

Default: master

capture_error_stacktraces
Record full stacktraces for PHP errors.

Default: true

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

Default: null

environment
Environment name, e.g. `'production'` or `'development'`
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)

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 overridiing, 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

Example use of 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
);
?>

Example use of 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';
?>

Related projects

A Laravel-specific package is available for integrating with Laravel: Laravel-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

laykou/rollbar-php 适用场景与选型建议

laykou/rollbar-php 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 132 次下载、GitHub Stars 达 0, 最近一次更新时间为 2015 年 02 月 14 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「logging」 「errors」 「exceptions」 「debugging」 「monitoring」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 laykou/rollbar-php 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 laykou/rollbar-php 我们能提供哪些服务?
定制开发 / 二次开发

基于 laykou/rollbar-php 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 132
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 21
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 2
  • Forks: 125
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2015-02-14