> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# 扩展包中的自定义 Pulse 记录器

> 介绍如何使用 Laravel Pulse 的记录器，将扩展包自身的事件汇总到仪表盘。说明通过 listen 订阅事件、使用 Pulse::record 进行汇总、ignore 与 sample_rate 的配置以及异常处理。

Laravel Pulse 会在仪表盘上汇总请求、查询、任务等信息。当扩展包执行自己的处理时，可以通过自定义记录器在 Pulse 中监控这些处理的次数和耗时。

本指南将构建一个记录器，订阅扩展包分发的事件并记录其次数和耗时。Pulse 的基本用法请参阅 [Pulse](https://kawax.biz/zh-CN/pulse.md)。

> [!NOTE]
>
> 本指南基于 Pulse 1.11.0 的源代码。示例中的 `ReportGenerated` 事件是用于说明的假想类。在实际的扩展包中，请替换为你自己的事件。

## 处理流程

记录器接收到事件后，会把记录累积到 Pulse 的缓冲区中。缓冲区会在采集（ingest）时统一保存。

```mermaid theme={null}
flowchart LR
    A["触发事件"] --> B["listen 调用<br>record"]
    B --> C["Pulse::record<br>创建 Entry"]
    C --> D["Pulse 缓冲区"]
    D --> E["在 ingest 时保存"]
    E --> F["pulse_entries"]
    E --> G["pulse_aggregates"]
    F --> H["在仪表盘中显示"]
    G --> H
```

## 创建记录器

记录器在 `listen` 属性中声明要订阅的事件，并在 `record()` 方法中实现处理。下面的示例记录扩展包分发的 `ReportGenerated` 事件。假设该事件拥有 `$type` 和 `$durationMs` 属性。

```php theme={null}
<?php

namespace Acme\Reports\Pulse;

use Acme\Reports\Events\ReportGenerated;
use Laravel\Pulse\Facades\Pulse;
use Laravel\Pulse\Recorders\Concerns\Ignores;
use Laravel\Pulse\Recorders\Concerns\Sampling;

class ReportGenerationRecorder
{
    use Ignores, Sampling;

    public array $listen = [
        ReportGenerated::class,
    ];

    public function record(ReportGenerated $event): void
    {
        if ($this->shouldIgnore($event->type) || ! $this->shouldSample()) {
            return;
        }

        Pulse::record(
            type: 'report_generation',
            key: $event->type,
            value: $event->durationMs,
        )->count()->avg()->max();
    }
}
```

`Ignores` 和 `Sampling` trait 会读取下文介绍的 `ignore` 和 `sample_rate` 配置。

## 在应用中注册记录器

在应用的 `config/pulse.php` 的 `recorders` 数组中注册记录器。以记录器的类名作为键，并以启用标志和配置作为值。

```php theme={null}
'recorders' => [
    // 现有的记录器保持不变
    Acme\Reports\Pulse\ReportGenerationRecorder::class => [
        'enabled' => true,
        'sample_rate' => 1,
        'ignore' => ['/^debug_/'],
    ],
],
```

当 `pulse.enabled` 开启时，`PulseServiceProvider` 会读取 `pulse.recorders` 并注册记录器。`enabled` 为 `false` 的记录器不会被注册。与其由扩展包自动改写此配置，不如在安装说明中展示配置示例更安全。

## 汇总的种类

`Pulse::record()` 返回一个 `Entry`。链式调用 `count()`、`min()`、`max()`、`sum()` 或 `avg()` 后，对应的汇总会保存到 `pulse_aggregates` 中。

| 方法 | 保存的值 |
| - | - |
| `count()` | 次数 |
| `min()` | 最小值 |
| `max()` | 最大值 |
| `sum()` | 总和 |
| `avg()` | 平均值 |
| `onlyBuckets()` | 只保存汇总结果，不在 `pulse_entries` 中保留单条记录 |

`min()`、`max()`、`sum()` 和 `avg()` 会使用 `value` 进行计算。仅使用 `count()` 时不需要 `value`。

当事件触发非常频繁时，`onlyBuckets()` 可以减少 `pulse_entries` 的行数。

## 保存字符串值

如果要保存最新状态之类的字符串而不是汇总数值，请使用 `Pulse::set()`。该值会保存到 `pulse_values` 表中。

```php theme={null}
use Laravel\Pulse\Facades\Pulse;

Pulse::set('report_status', $event->type, $event->status);
```

`value` 必须以 `string` 形式传入。

## 延迟耗时处理

传给 `Pulse::lazy()` 的闭包不会立即执行，而是在 Pulse 采集数据时执行。当记录比较耗时、希望在发送响应之后再执行时使用。

```php theme={null}
Pulse::lazy(function () use ($event) {
    Pulse::record('report_size', $event->type, $event->rows)->sum();
});
```

## 记录已认证用户

需要已认证用户的标识符时，请使用 `Pulse::resolveAuthenticatedUserId()`。没有已认证用户时返回 `null`。

```php theme={null}
$userId = Pulse::resolveAuthenticatedUserId();
```

## 排除、采样与过滤

可以使用以下四种方式减少记录量：

* `ignore` 配置：当传给 `shouldIgnore()` 的值与任一正则表达式匹配时跳过记录。在上面的示例中，`$event->type` 与 `/^debug_/` 匹配的事件会被跳过。
* `sample_rate` 配置：由 `shouldSample()` 检查。`1` 记录所有事件，`0.1` 大约记录 10%。
* `Pulse::ignore()`：在回调内禁用记录，并返回回调的结果。
* `Pulse::filter()`：在保存前接收每个 `Entry` 或 `Value`，只保存返回 `true` 的项目。

## 异常处理

Pulse 会用 `rescue()` 包裹记录器的处理和采集。记录器内抛出的异常不会传到应用中。如果没有设置 `handleExceptionsUsing()`，异常会被静默丢弃。如需报告异常，请在应用中进行配置。

```php theme={null}
use Laravel\Pulse\Facades\Pulse;

Pulse::handleExceptionsUsing(fn (Throwable $e) => report($e));
```

## 测试

测试记录器时，可以分发事件、调用 `Pulse::ingest()`，然后检查保存的行。下面的示例由 Pulse 的源代码推导而来，尚未实际运行。请确保测试环境中 `pulse.enabled` 已开启。

```php theme={null}
use Acme\Reports\Events\ReportGenerated;
use Laravel\Pulse\Facades\Pulse;

it('records ReportGenerated in pulse_entries', function () {
    event(new ReportGenerated(type: 'monthly', durationMs: 120));

    Pulse::ingest();

    $this->assertDatabaseHas('pulse_entries', [
        'type' => 'report_generation',
        'key' => 'monthly',
        'value' => 120,
    ]);
});
```

## 键的设计

`key` 是汇总的单位。如果使用用户 ID 或 URL 这类会无限增长的值，数据量会增加，汇总结果也会难以阅读。`key` 请使用事件类型或进程名称这类种类有限的值。


## Related topics

- [进阶主题](https://kawax.biz/zh-CN/advanced/index.md)
- [在扩展包中注册字符串验证规则](https://kawax.biz/zh-CN/advanced/package-validation-extensions.md)
- [包的自定义通知渠道与投递验证](https://kawax.biz/zh-CN/advanced/package-notification-channels.md)
- [Laravel Pulse](https://kawax.biz/zh-CN/pulse.md)
- [包的自定义 UserProvider](https://kawax.biz/zh-CN/advanced/package-user-providers.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.