laxity7/yii2-sentry
一个允许通过 Yii2 日志方法传递数据数组的 Sentry 组件
0.2.1
2016-11-22 01:14 UTC
Requires
- php: >=5.4.0
- sentry/sentry: ^1.5
- yiisoft/yii2: ^2.0
This package is auto-updated.
Last update: 2024-09-16 15:58:42 UTC
README
Yii2 Sentry 组件,允许统一数组格式传递参数到 Sentry 日志目标和其他日志目标。传递数组作为日志消息是适合那些想使用 Logstash、ElasticSearch 等工具来获取这些数据后续统计推断的做法。
安装
php composer.phar require laxity7/yii2-sentry
在配置文件中
'bootstrap' => ['log', 'raven'], 'components' => [ 'raven' => [ 'class' => 'laxity7\sentry\ErrorHandler', 'dsn' => '', // Sentry DSN ], 'log' => [ 'targets' => [ [ 'class' => 'laxity7\sentry\Target', 'levels' => ['error', 'warning'], 'dsn' => '', // Sentry DSN ], ], ], ],
如果应用程序没有 raven 组件,则该组件将不会尝试向 Sentry 发送消息。这在开发环境中非常有用,例如。
使用
异常和 PHP 错误可以轻松捕获。标准的 Yii::(error|warning|info|trace) 日志仍然按常规工作,但你也可以使用以下格式
Yii::warning([ // event name that will be sent to Sentry 'msg' => 'SomeWarning', // extra data for the event 'data' => [ 'userId' => Yii::$app->user->id, 'someDataOnWarningSituation' => $controller->state, 'modelThatCausedFailure' => $model->attributes, ], ], 'eventCategory');
或者你可以用下面的例子中的 Log::warning 替换,因为异常参数不是必需的。请注意,eventCategory 不会发送到 Sentry,只用于日志消息的路由和过滤。
在任何需要记录捕获的异常(带堆栈跟踪和附加数据)的地方使用
use laxity7\sentry\Log; // some code here try { $model->save(); } catch (\Exception $e) { Log::warning([ // event name that will be sent to Sentry 'msg' => 'ExceptionWarning', // extra data for the event 'data' => [ 'userId' => Yii::$app->user->id, 'someDataOnWarningSituation' => $controller->state, 'modelThatCausedFailure' => $model->attributes, ], ], 'exceptionCategory', $e); }
Log 中有针对四个 Yii 静态方法的代理方法:error、warning、info、trace。如果 $e 不为空,组件期望它是一个异常,并在调用相应的 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; use yii\log\Logger; use yii\helpers\Json; class SyslogJsonTarget extends \yii\log\SyslogTarget { /** * @inheritdoc */ public function formatMessage($message) { list($text, $level, $category, $timestamp) = $message; $level = Logger::getLevelName($level); if (!is_string($text)) { $text = Json::encode($text); } else { $text = Json::encode(['rawstring' => $text]); } $prefix = $this->getMessagePrefix($message); return "{$prefix}[$level][$category] $text"; } }
数据注意事项
- 避免在数组中传递无法序列化的资源或对象,或者重写
formatMessage来处理这种情况,例如尝试序列化 PDO 实例将引发致命的 PHP 错误。原生的 Yii 日志目标将尝试序列化这些内容。你可以查看 http://github.com/raven/raven 来了解它如何清理和处理这些情况,并使用它的静态方法。 - 还可以检查 raven 如何过滤出私人数据,如密码或敏感财务信息。