当前位置: 首页 > 工具软件 > Laravel-Zero > 使用案例 >

Laravel 5.x 集成Sentry

公冶俊达
2023-12-01

Laravel通过本地包装,sentry-laravel得到支持。

一、Laravel 5.x

安装sentry / sentry-laravel包:

$ composer require sentry/sentry-laravel

如果您使用的是Laravel 5.4或更早版本,则需要在config / app.php中添加以下内容(对于Laravel 5.5+,这些将由Laravel自动发现):

'providers' => array(
    // ...
    Sentry\SentryLaravel\SentryLaravelServiceProvider::class,
)

'aliases' => array(
    // ...
    'Sentry' => Sentry\SentryLaravel\SentryFacade::class,
)

将Sentry报告添加到App / Exceptions / Handler.php:

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

    parent::report($exception);
}

创建Sentry配置文件(config / sentry.php):

$ php artisan vendor:publish --provider="Sentry\SentryLaravel\SentryLaravelServiceProvider"

将您的DSN添加到.env:

SENTRY_LARAVEL_DSN=https://<key>@sentry.io/<project>

最后,如果您希望连接用户反馈,可以通过在resources / views / errors / 500.blade.php中创建自定义错误视图来实现。

对于Laravel 5高达5.4,您需要打开App / Exceptions / Handler.php并扩展render方法以确保500错误正确呈现为视图,在5.5+中不再需要此步骤,您可以向前跳过到下一个:

<?php

use Symfony\Component\HttpKernel\Exception\HttpException;

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

        parent::report($exception);
    }

    public function render($request, Exception $exception)
    {
        // Convert all non-http exceptions to a proper 500 http exception
        // if we don't do this exceptions are shown as a default template
        // instead of our own view in resources/views/errors/500.blade.php
        if ($this->shouldReport($exception) && !$this->isHttpException($exception) && !config('app.debug')) {
            $exception = new HttpException(500, 'Whoops!');
        }

        return parent::render($request, $exception);
    }
}

接下来,创建resources / views / errors / 500.blade.php,并嵌入反馈代码:

<div class="content">
    <div class="title">Something went wrong.</div>

    @if(app()->bound('sentry') && !empty(Sentry::getLastEventID()))
        <div class="subtitle">Error ID: {{ Sentry::getLastEventID() }}</div>

        <!-- Sentry JS SDK 2.1.+ required -->
        <script src="https://cdn.ravenjs.com/3.3.0/raven.min.js"></script>

        <script>
            Raven.showReportDialog({
                eventId: '{{ Sentry::getLastEventID() }}',
                // use the public DSN (dont include your secret!)
                dsn: 'https://<key>@sentry.io/<project>',
                user: {
                    'name': 'Jane Doe',
                    'email': 'jane.doe@example.com',
                }
            });
        </script>
    @endif
</div>

 

 

 

 

 

 

 

 

 

 

 

 

 类似资料: