如何在PHP Laravel中开启Sentry HTTP客户端错误追踪?
Laravel + Sentry 追踪HTTP客户端错误的实现方案
目前Sentry的Laravel SDK没有像.NET那样提供一键开启HTTP客户端错误追踪的配置项,但可以通过以下两种方式实现等效功能:
1. 日志捕获结合Sentry自动上报
Laravel HTTP客户端的请求错误会触发GuzzleException相关日志,只要确保Sentry日志通道配置正常,错误日志会自动上报到Sentry。你还可以在捕获异常时补充请求上下文信息,让上报内容更完整:
try { $response = Http::get('https://example.com/api'); } catch (\GuzzleHttp\Exception\GuzzleException $e) { logger()->error('HTTP请求失败', [ '请求地址' => 'https://example.com/api', '错误码' => $e->getCode(), '错误信息' => $e->getMessage(), '堆栈追踪' => $e->getTraceAsString() ]); throw $e; }
2. 自定义HTTP客户端中间件(自动化方案)
通过Laravel HTTP客户端的全局中间件,拦截所有请求和响应,当响应状态码为错误(4xx/5xx)或请求抛出异常时,自动向Sentry上报事件:
步骤1:创建中间件
// app/Http/Middleware/SentryHttpClientMiddleware.php namespace App\Http\Middleware; use GuzzleHttp\Promise\PromiseInterface; use Illuminate\Http\Client\PendingRequest; use Illuminate\Http\Client\Response; use Sentry\State\Scope; class SentryHttpClientMiddleware { public function handle(PendingRequest $request, $next) { $response = $next($request); // 处理同步请求响应 if ($response instanceof Response && $response->failed()) { $this->reportErrorToSentry($request, $response); } // 处理异步请求响应 if ($response instanceof PromiseInterface) { return $response->then(function (Response $response) use ($request) { if ($response->failed()) { $this->reportErrorToSentry($request, $response); } return $response; }); } return $response; } protected function reportErrorToSentry(PendingRequest $request, Response $response) { \Sentry\captureMessage( "HTTP客户端请求失败: {$response->status()}", \Sentry\Severity::error(), function (Scope $scope) use ($request, $response) { $scope->setContext('http请求详情', [ '请求方法' => $request->method(), '请求地址' => (string)$request->url(), '请求头' => $request->headers(), '响应状态码' => $response->status(), '响应内容' => $response->body(), ]); } ); } }
步骤2:注册全局中间件
在AppServiceProvider的boot方法中添加:
use Illuminate\Support\Facades\Http; use App\Http\Middleware\SentryHttpClientMiddleware; public function boot() { Http::globalMiddleware([ SentryHttpClientMiddleware::class, ]); }
补充说明
你提到的breadcrumbs.http_client_requests配置仅用于将HTTP请求记录为Sentry事件的面包屑,不会主动上报错误事件。上述方案中,自定义中间件的方式更自动化,无需在每个请求处手动编写捕获逻辑,更贴近.NET平台的配置效果。
内容的提问来源于stack exchange,提问作者Vladimir Nikitin
相关产品推荐
相关产品推荐

