介绍
在开始之前,我们需要到 Sentry 官网注册一个账号,获取 API 认证信息,Sentry 通过 Project(项目)、Team(团队)、Member(成员) 三种关系管理应用,一个项目/应用可以被多个不同团队订阅,一个团队可能包含多个成员,免费版本仅支持一个用户,我们以免费版本为例进行演示。
Laravel 接入 Sentry 非常简单,安装引导程序新增团队及关联成员,确认告警邮箱,然后新建项目,新建项目页面包含了对 Laravel 的支持:
安装
选择 Laravel,然后给项目起个名字,最后点击创建按钮。创建成功后页面会跳转到 Laravel 应用接入指南,我们按照这个指南来操作即可。首先通过 Composer 安装对应扩展包:
//安装
composer require sentry/sentry-laravel
//对于 Laravel 5.5+ 版本,扩展包会自动发现,无需注册,然后将配置文件发布到 config 目录下:
php artisan vendor:publish --provider="Sentry\SentryLaravel\SentryLaravelServiceProvider"
//编辑 .env 文件,将指南页面中的配置项目拷贝进去:
SENTRY_LARAVEL_DSN=这里是你的DSN配置值
使用
创建项目
官方配置方式
接下里,也是最后一步,编辑 App/Exceptions/Handler.php 的 report 方法:
public function report(Exception $exception)
{
if (app()->bound('sentry') && $this->shouldReport($exception)) {
app('sentry')->captureException($exception);
}
parent::report($exception);
}
日志系统配置
laravel 5.6 版本引入了日志频道功能,所以也可以通过将异常日志记录到 Sentry 中来实现类似的功能;这样做的好处是不需要额外的代码编辑,只需修改 config/logging.php 配置即可。首先在 .env 中修改 LOG_CHANNEL 为 stack,然后修改 config/logging.php 的 channels 配置如下(我是将 NOTICE 级别以上日志记录到 Sentry)
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['daily', 'sentry'],
],
... // 其他自带配置项
'sentry' => [
'driver' => 'sentry',
// The minimum monolog logging level at which this handler will be triggered
'level' => \Monolog\Logger::NOTICE,
// For example: `\Monolog\Logger::ERROR`
'bubble' => true, // Whether the messages that are handled can bubble up the stack or not
],
]
示例
就是这么简单,接入之后,坐等线上第一条异常告警信息吧,告警邮件包含了异常详情,你也可以点击链接到 Sentry 官网查看明细,异常列表长这样: