> ## 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 會在儀表板上彙總請求、查詢、Job 等資訊。當套件執行自己的處理時，可以透過自訂記錄器在 Pulse 中監控這些處理的次數與耗時。

本指南將建立一個記錄器，訂閱套件分派的事件並記錄其次數與耗時。Pulse 的基本用法請參閱 [Pulse](https://kawax.biz/zh-TW/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-TW/advanced/index.md)
- [套件的自訂 Session 驅動](https://kawax.biz/zh-TW/advanced/package-session-drivers.md)
- [套件的自訂通知頻道與傳送驗證](https://kawax.biz/zh-TW/advanced/package-notification-channels.md)
- [套件的自訂 UserProvider](https://kawax.biz/zh-TW/advanced/package-user-providers.md)
- [套件的自訂快取儲存與契約](https://kawax.biz/zh-TW/advanced/package-cache-drivers.md)


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