sheershoff / yii2-sentry-component
一个允许通过 Yii2 日志方法传递数据数组的 Sentry 组件
1.0.8
2016-05-26 07:46 UTC
Requires
- php: >=5.4.0
- raven/raven: ~0.10
- yiisoft/yii2: *
README
此分支已被放弃,仅保留给仍然使用它的人(如果有的话)。请继续使用https://github.com/E96/yii2-sentry。
Yii2 sentry 组件
Yii2 Sentry 组件允许以统一数组格式传递参数到 Sentry 日志目标和其它日志目标。将数组作为日志消息传递的能力适合那些想使用 Logstash、ElasticSearch 等工具对这些数据进行统计分析的人。
安装
php composer.phar require sheershoff/yii2-sentry-component:dev-master
在配置文件中
'bootstrap' => ['log', 'raven'], 'components' => [ 'raven' => [ 'class' => 'sheershoff\sentry\ErrorHandler', 'dsn' => '', // Sentry DSN ], 'log' => [ 'targets' => [ [ 'class' => 'sheershoff\sentry\Target', 'levels' => ['error', 'warning'], 'dsn' => '', // Sentry DSN ] ], ], ]
如果应用程序没有 raven
组件,则该组件将不会尝试向 Sentry 发送消息。这对于开发环境来说很有用,例如。
用法
异常和 PHP 错误可以轻松捕获。标准的 Yii::(error|warning|info|trace)
日志记录工作正常,但你也可以使用以下格式
Yii::warning([ 'msg' => 'SomeWarning', // event name that will be sent to Sentry 'data' => [ // extra data for the event 'userId' => Yii::$app->user->id, 'someDataOnWarningSituation' => $controller->state, 'modelThatCausedFailure' => $model->attributes, ], ], 'eventCategory');
或者你可以像下面的异常示例一样用 Log::warning
替换,因为异常参数不是必需的。注意,eventCategory
不会发送到 Sentry,它只用于日志消息的路由和过滤。
无论何时需要记录捕获的异常以及堆栈跟踪和附加数据,请使用
use sheershoff\sentry\Log; // some code here try{ $model1->save(); }catch (\Exception $e){ Log::warning([ 'msg' => 'ExceptionWarning', // event name that will be sent to Sentry 'data' => [ // extra data for the event 'userId' => Yii::$app->user->id, 'someDataOnWarningSituation' => $controller->state, 'modelThatCausedFailure' => $model->attributes, ], ], 'exceptionCategory', $e); }
Log
中存在四个 Yii 静态方法的代理方法: error
、warning
、info
、trace
。如果 $e
不是 null,则组件期望它是一个异常,并在调用相应的 Yii 方法后捕获异常以发送到 Sentry。
以下使用情况也是可能的
SentryHelper::extraData($task->attributes); throw new Exception('unknown task type');
或者只是捕获带有完整堆栈跟踪的消息
try { throw new Exception('FAIL'); } catch (Exception $e) { SentryHelper::captureWithMessage('Fail to save model', $e); }
其他日志目标
要使用该组件的功能,你应该记住,其他日志目标将接收到日志消息中的数组而不是字符串。你可以创建一个代理类,重新定义父类 LogTarget
的 formatMessage
方法,例如
namespace common\components; use Yii; class SyslogJsonTarget extends \yii\log\SyslogTarget { /** * @inheritdoc */ public function formatMessage($message) { list($text, $level, $category, $timestamp) = $message; $level = \yii\log\Logger::getLevelName($level); if (!is_string($text)) { $text = \yii\helpers\Json::encode($text); } else { $text = \yii\helpers\Json::encode(['rawstring' => $text]); } $prefix = $this->getMessagePrefix($message); return "{$prefix}[$level][$category] $text"; } }
数据注意事项
- 避免在数组中传递无法序列化的资源或对象,或者重写
formatMessage
来处理这种情况,例如尝试序列化 PDO 实例将引发致命 PHP 错误。本地的 Yii 日志目标将尝试序列化它。可以查看 http://github.com/raven/raven 来了解它是如何清理和处理这些情况的,并使用它的静态方法。 - 还可以查看 raven 如何过滤掉私有数据,如密码或敏感的财务信息。