Laravel集成Sentry需安装sentry/sentry-laravel包,注册服务提供者和Facade,配置.env中的SENTRY_LARAVEL_DSN,在config/logging.php添加driver为sentry的日志通道并设置level,可选stack组合,最后在App/Exceptions/Handler.php的report方法中调用\Sentry\captureException($exception)捕获异常,也可用\Sentry\captureMessage手动上报,实现错误自动追踪。
Laravel 可以通过集成 Sentry 提供的 SDK,将应用日志自动发送到 Sentry 外部服务,便于错误追踪和异常监控。实现过程主要包括安装 Sentry 客户端、配置 Laravel 日志通道以及设置异常处理。
使用 Composer 安装官方 Sentry-Laravel 包:
composer require sentry/sentry-laravel
安装完成后,在 config/app.php 中注册服务提供者(Laravel 5.5+ 可跳过,已支持自动发现):
'providers' => [ Sentry\Laravel\ServiceProvider::class, ],
同时添加 Facade(可选,用于手动捕获异常):
'aliases' => [ 'Sentry' => Sentry\Laravel\Facade::class, ],
在 .env 文件中添加 Sentry 的 DSN 地址:
SENTRY_LARAVEL_DSN=https://your-key@o123456.ingest.sentry.io/1234567
确保这个 DSN 来自你的 Sentry 项目设置页面。你也可以在 config/services.php 中配置其他选项,例如环境、版本等。
Laravel 使用 Monolog 驱动日志系统,可以通过创建一个自定义日志通道将错误发送到 Sentry。
打开 config/logging.php,在 'channels'
中添加一个新的 stack 或 direct channel:
'sentry' => [ 'driver' => 'sentry', 'level' => 'error', // 可设为 debug, info, error 等级别 'bubble' => true, ],
然后你可以将默认日志通道切换为 Sentry,或与其他通道组合使用。例如在 stack
中包含 Sentry:
'stack' => [ 'driver' => 'stack', 'channels' => ['single', 'sentry'], 'ignore_exceptions' => false, ],
这样,所有记录的日志在满足 level 条件时都会被发送到 Sentry。
Laravel 默认会在 App/Exceptions/Handler.php 中报告异常。修改 report()
方法,确保非本地环境下的异常被发送:
public function report(Throwable $exception) { if ($this->shouldReport($exception)) { \Sentry\captureException($exception); } parent::report($exception); }
你也可以在代码中手动发送信息到 Sentry:
\Sentry\captureMessage("Something went wrong");
基本上就这些。完成配置后,Laravel 应用中的错误和指定级别的日志会自动发送到 Sentry,帮助你实时监控线上问题。确保不要在生产环境之外误报太多噪音数据。
以上就是laravel如何将日志发送到外部服务如Sentry_Laravel日志发送到Sentry外部服务方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号