ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
## Sentry [Sentry](https://sentry.io/) 是一个日志平台,分为客户端和服务端,客户端(目前客户端有Python, PHP,C#, Ruby等多种语言)就嵌入在你的应用程序中间,程序出现异常就向服务端发送消息,服务端将消息记录到数据库中并提供一个web节目方便查看。Sentry由python编写,源码开放,性能卓越,易于扩展,目前著名的用户有 Disqus, Path, mozilla, Pinterest 等。 ## 如何接入 首先安装 Sentry PHP 库: ~~~ composer require sentry/sdk ~~~ 首先由于 [sentry/sdk](https://packagist.org/packages/sentry/sdk) 是基于 GuzzleHttp 开发的,因为 GuzzleHttp 无法直接在 Swoole 协程中使用,所以需要先安装 [Mix Guzzle](https://github.com/mix-php/guzzle),该库能在不修改源码的情况下让 GuzzleHttp 协程化。 ~~~ composer require mix/guzzle ~~~ 然后我们查看一下框架错误组件的依赖配置: - [manifest/beans/error.php](https://github.com/mix-php/mix-skeleton/blob/master/manifest/beans/error.php) 在配置中我们能看到注入了一个 `dispatcher` 的属性,是一个事件调度器,而 [mix/console](https://github.com/mix-php/console) 会在每次捕获到异常的时候调用该调度器,触发: - `Mix\Console\Event\HandleExceptionEvent::class` 事件:包含一个 `$exception` 的属性,就是当次抛出的异常对象。 我们首先创建一个监听器: ~~~ <?php namespace App\Common\Listeners; use Mix\Console\Event\HandleExceptionEvent; use Mix\Event\ListenerInterface; /** * Class ExceptionListener * @package App\Common\Listeners * @author liu,jian <coder.keda@gmail.com> */ class ExceptionListener implements ListenerInterface { /** * 监听的事件 * @return array */ public function events(): array { // 要监听的事件数组,可监听多个事件 return [ HandleExceptionEvent::class, ]; } /** * 处理事件 * @param object $event */ public function process(object $event) { // 事件触发后,会执行该方法 if (!$event instanceof HandleExceptionEvent) { return; } \Sentry\init(['dsn' => 'https://<key>@<organization>.ingest.sentry.io/<project>' ]); \Sentry\captureException($event->exception); } } ~~~ 然后将监听器注册到事件调度器中: - [manifest/beans/event.php#L15](https://github.com/mix-php/mix-skeleton/blob/master/manifest/beans/event.php#L15)