使用

了解如何自动报告错误、异常和拒绝,以及如何手动捕获错误和启用消息捕获。

Sentry 的 SDK 钩入您的运行时环境,并自动报告错误、异常和拒绝。

最常见的捕获形式是捕获错误。可以捕获为错误的内容因平台而异。通常,如果您有一个看起来像异常的东西,它可以被捕获。对于某些 SDK,您可以省略 capture_exception 的参数,Sentry 将尝试捕获当前异常。手动向 Sentry 报告错误或消息也很有用。

除了捕获之外,您还可以记录导致事件的面包屑。面包屑与事件不同:它们不会在 Sentry 中创建事件,而是会被缓冲,直到发送下一个事件。了解更多关于面包屑的信息,请参阅我们的 面包屑文档

在 Laravel 中,您可以将错误对象传递给 captureException() 以将其捕获为事件。也可以抛出字符串作为错误,在这种情况下无法记录回溯。

在 PHP 中,您可以捕获已捕获的异常或使用 captureLastError 捕获最后一个错误。

Copied
try {
    $this->functionFailsForSure();
} catch (\Throwable $exception) {
    \Sentry\captureException($exception);
}

另一个常见的操作是捕获纯文本消息。消息是应发送到 Sentry 的文本信息。通常,我们的 SDK 不会自动捕获消息,但您可以手动捕获它们。

消息会显示在您的问题流中,消息本身作为问题名称。

Copied
\Sentry\captureMessage('Something went wrong');

sentry-laravel 的版本 1.5.0 开始,您可以通过修改客户端构建器来自定义 PHP SDK 客户端的构建方式。

您可能希望这样做,例如,替换传输或更改仅在构建客户端时可以更改的序列化选项。

下面的代码片段必须放在服务提供者的 register 方法中(例如您的 AppServiceProvider)。

在本示例中,我们将默认序列化的 maxDepth 增加到 5。

Copied
use Sentry\Serializer\Serializer;
use Sentry\ClientBuilderInterface;

$this->app->extend(ClientBuilderInterface::class, function (ClientBuilderInterface $clientBuilder) {
    $clientBuilder->setSerializer(new Serializer($clientBuilder->getOptions(), 5));

    return $clientBuilder;
});

从 Laravel 5.3 开始,如果在 config/sentry.php 中将 send_default_pii 选项设置为 true,我们可以自动将经过身份验证的用户 ID 添加到范围中。

将更多用户上下文添加到范围中的机制将根据您使用的 Laravel 版本而有所不同,但总体方法是相同的。找到一个合适的应用程序入口点,在该点可以访问您想要添加的上下文,理想情况下是在处理的早期阶段。

在以下示例中,我们将使用中间件在用户登录时添加用户信息:

Copied
namespace App\Http\Middleware;

use Closure;
use Sentry\State\Scope;

class SentryContext
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (auth()->check() && app()->bound('sentry')) {
            \Sentry\configureScope(function (Scope $scope): void {
                $scope->setUser([
                    'id' => auth()->user()->id,
                    'email' => auth()->user()->email,
                ]);
            });
        }

        return $next($request);
    }
}

要将 Sentry 配置为日志通道,请将以下配置添加到 config/logging.php 文件中的 channels 部分。 如果此文件不存在,请运行 php artisan config:publish logging 来发布它。

config/logging.php
Copied
'channels' => [
    // ...
    'sentry' => [
        'driver' => 'sentry',
    ],
],

在配置了 Sentry 日志通道后,您可以通过修改日志堆栈来配置应用程序,以便同时将日志记录到日志文件和 Sentry:

config/logging.php
Copied
'channels' => [
    'stack' => [
        'driver' => 'stack',
        // Add the Sentry log channel to the stack
        'channels' => ['single', 'sentry'],
    ],
    //...
],

可选地,您可以设置 日志级别 以及事件是否应在驱动程序上冒泡:

config/logging.php
Copied
'channels' => [
    // ...
    'sentry' => [
        'driver' => 'sentry',
        // The minimum logging level at which this handler will be triggered
        // Available levels: debug, info, notice, warning, error, critical, alert, emergency
        'level' => env('LOG_LEVEL', 'error'),
        'bubble' => true, // Whether the messages that are handled can bubble up the stack or not
    ],
],

当您在任务类中定义了 failed 方法(文档)时,该 failed 方法的行为类似于任务在 try {} catch (\Exception $e) {} 中运行。这将阻止异常报告,导致任务失败未被报告给 Sentry。

这可能是预期的行为,因为您的任务有时会由于无法访问的 API 或其他预期的失败而失败。如果您仍然希望将异常报告给 Sentry,可以在 failed 方法中实现以下内容:

Copied
/**
 * The job failed to process.
 *
 * @param \Exception $exception
 *
 * @return void
 */
public function failed(\Exception $exception)
{
    // Send user notification of failure, etc...

    if (app()->bound('sentry')) {
        app('sentry')->captureException($exception);
    }
}

为了在 Sentry 中过滤多个日志通道,您可以在日志通道中添加 name 属性。 它将在 Sentry 中显示为可过滤的 logger 标签。

例如:

config/logging.php
Copied
'channels' => [
    'my_stacked_channel' => [
        'driver' => 'stack',
        'channels' => ['single', 'sentry'],
        'name' => 'my-channel'
    ],
    //...
],

因此,您可以将错误记录到您的通道:

Copied
\Log::channel('my_stacked_channel')->error('My error');

Sentry 的 logger 标签现在包含通道的 name。您可以过滤 "my-channel" 值。

如果您有其他也命名为 Sentry 的包,您需要创建自己的服务提供者并扩展我们的服务提供者,以防止名称冲突。

Copied
<?php

namespace App\Support;

class SentryLaravelServiceProvider extends \Sentry\Laravel\ServiceProvider
{
    public static $abstract = 'sentry-laravel';
}

然后您可以将此服务提供者添加到 config/app.php

config/app.php
Copied
'providers' => array(
    // ...
    App\Support\SentryLaravelServiceProvider::class,
)

可选地,如果您想使用门面(facade),您还需要扩展或创建一个新的门面。

Copied
<?php

namespace App\Support;

class SentryLaravelFacade extends \Sentry\Laravel\Facade
{
    protected static function getFacadeAccessor()
    {
        return 'sentry-laravel';
    }
}

并将该门面添加到您的 config/app.php

config/app.php
Copied
'aliases' => array(
    // ...
    'SentryLaravel' => App\Support\SentryLaravelFacade::class,
)

在添加了您自己的服务提供者后,运行 php artisan vendor:publish --provider="App\Support\SentryLaravelServiceProvider" 会将 Sentry 配置文件发布到您选择的名称(在上面的例子中为 config/sentry-laravel.php),以防止与可能被其他包使用的 config/sentry.php 配置文件发生冲突。

如果您按照上述常规安装说明进行操作(建议这样做),请确保将 app('sentry') 替换为 app('sentry-laravel')

在上面的示例中,命名空间 \App\Support 可以是您想要的任何命名空间。

composer.json
Copied
"extra": {
    "laravel": {
        "dont-discover": ["sentry/sentry-laravel"]
    }
}