目录

Laravel/Lumen 项目接入 Sentry 异常监控

目录
  1. 首先安装 sentry SDK 包:

$ composer require sentry/sentry-laravel:1.5.0

如果使用的 5.5 以上的框架会自动发现包并加载(Lumen 需手动注册),我们目前项目都是 5.5 以上所以无需单独配置。

Lumen 注册方法是在 bootstrap/app.php 中添加:

1
2
3
4
5
6
7
8

$app->register('Sentry\Laravel\ServiceProvider');

# Sentry must be registered before routes are included

# 必须在路由加载前注册

require __DIR__ . '/../app/Http/routes.php';
  1. 然后将报告方法加入 App/Exceptions/Handler.php ​中:
1
2
3
4
5
6
7
8
9

public function report(Exception $exception){
    if (app()->bound('sentry') && $this->shouldReport($exception)) {
        app('sentry')->captureException($exception);
    }

    parent::report($exception);

}

​3. 执行 php artisan vendor:publish --provider="Sentry\Laravel\ServiceProvider"​ 将配置文件加入 config 文件夹中(Lumen 需要手动复制或创建),将 sentry 中获得的 DSN 链接配置进文件:

'dsn' => env('SENTRY_LARAVEL_DSN', null),

如果是 null,sentry SDK 将不触发上报。

需在 .env 中添加 SENTRY_LARAVEL_DSN=https://<key>@sentry.io/<project> 配置,具体地址是 Sentry 中项目分配。

  1. 测试是否接入成功可以使用在路由文件中新建一个路由主动抛出异常
1
2
3
4
Route::get('/debug-sentry', function () {
    throw new Exception('My first Sentry error!');

});