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

# Laravel Pulse

> 說明使用 Laravel Pulse 導入應用程式監控儀表板的方法與設定。廣泛涵蓋 recorder、取樣、自訂卡片的建立。

## 什麼是 Laravel Pulse

[Laravel Pulse](https://github.com/laravel/pulse) 是可一眼掌握應用程式效能與使用狀況的監控儀表板。
可用來找出慢速任務或慢速端點的瓶頸，或查詢最活躍的使用者。

### Telescope 與 Pulse 的差異

| 特徵   | Laravel Pulse | Laravel Telescope |
| ---- | ------------- | ----------------- |
| 目的   | 監控應用整體趨勢、集計資料 | 針對個別請求／事件的詳細除錯    |
| 資料   | 已集計的指標        | 個別事件的日誌           |
| 適用場景 | 正式環境的效能監控     | 開發／預備環境的除錯        |

<Info>
  個別事件的詳細除錯請使用 [Laravel Telescope](/zh-TW/blog/telescope-introduction)。
</Info>

### 資料流程圖

```mermaid theme={null}
flowchart LR
    A["Laravel 應用"] -->|事件偵測| B["Recorder<br>(Recorders)"]
    B -->|寫入 entry| C["資料庫<br>(Pulse 資料表)"]
    C -->|集計、顯示| D["儀表板<br>/pulse"]
    E["pulse:check<br>daemon"] -->|伺服器資訊| C
```

***

## 安裝

<Warning>
  Pulse 的第一方儲存實作需要 MySQL、MariaDB 或 PostgreSQL 資料庫。若使用其他資料庫引擎，請另外準備 MySQL、MariaDB 或 PostgreSQL 資料庫專用於 Pulse 資料。
</Warning>

<Steps>
  <Step title="安裝套件">
    使用 Composer 安裝 Pulse。

    ```shell theme={null}
    composer require laravel/pulse
    ```
  </Step>

  <Step title="公開設定檔與 migration">
    使用 `vendor:publish` Artisan 指令公開檔案。

    ```shell theme={null}
    php artisan vendor:publish --provider="Laravel\Pulse\PulseServiceProvider"
    ```
  </Step>

  <Step title="執行 migration">
    建立 Pulse 用於儲存資料的資料表。

    ```shell theme={null}
    php artisan migrate
    ```
  </Step>
</Steps>

migration 完成後，即可透過 `/pulse` 路由存取儀表板。

### 公開設定檔

亦可單獨公開設定檔進行自訂：

```shell theme={null}
php artisan vendor:publish --tag=pulse-config
```

***

## 存取儀表板

### 認證設定

預設只有 `local` 環境可存取儀表板。
在正式環境請自訂 `viewPulse` 認證 gate 以設定存取控制。

```php theme={null}
use App\Models\User;
use Illuminate\Support\Facades\Gate;

/**
 * Bootstrap any application services.
 */
public function boot(): void
{
    Gate::define('viewPulse', function (User $user) {
        return $user->isAdmin();
    });
}
```

將上述程式碼加入 `app/Providers/AppServiceProvider.php` 的 `boot` 方法。

### 儀表板自訂

可公開儀表板的 view，自訂卡片與版面配置。

```shell theme={null}
php artisan vendor:publish --tag=pulse-dashboard
```

公開後，編輯 `resources/views/vendor/pulse/dashboard.blade.php`。
儀表板以 [Livewire](https://livewire.laravel.com/) 運作，不需要建置 JavaScript 即可自訂。

```blade theme={null}
{{-- 全寬顯示 --}}
<x-pulse full-width>
    ...
</x-pulse>

{{-- 變更欄數 --}}
<x-pulse cols="16">
    ...
</x-pulse>
```

每個卡片可用 `cols` 與 `rows` 屬性調整大小與位置。

```blade theme={null}
<livewire:pulse.usage cols="4" rows="2" />
<livewire:pulse.slow-queries expand />
```

***

## Recorder

Recorder 會擷取應用程式的事件並記錄到 Pulse 資料庫。
在 `config/pulse.php` 的 `recorders` 區段管理設定。

### Requests / Slow Requests

`Requests` recorder 擷取進入應用程式的請求資訊。
可設定 slow route 的門檻（預設：1000ms）、取樣率，以及要忽略的路徑。

```php theme={null}
Recorders\SlowRequests::class => [
    // ...
    'threshold' => [
        '#^/admin/#' => 5000,
        'default' => env('PULSE_SLOW_REQUESTS_THRESHOLD', 1000),
    ],
],
```

### Slow Jobs

`SlowJobs` recorder 擷取超過門檻的緩慢 job（預設：1000ms）。
可為每個 job 設定不同的門檻。

```php theme={null}
Recorders\SlowJobs::class => [
    // ...
    'threshold' => [
        '#^App\\Jobs\\GenerateYearlyReports$#' => 5000,
        'default' => env('PULSE_SLOW_JOBS_THRESHOLD', 1000),
    ],
],
```

### Exceptions

`Exceptions` recorder 擷取應用程式發生的可回報例外。
會依例外類別與發生位置分群。

### Cache

`CacheInteractions` recorder 擷取快取的命中與未命中。
也可設定將相似 key 分群的正則表達式。

```php theme={null}
Recorders\CacheInteractions::class => [
    // ...
    'groups' => [
        '/:\d+/' => ':*',
    ],
],
```

### Queues

`Queues` recorder 擷取 queue 中 job 的吞吐量（已排入、處理中、已完成、已 release、失敗）。

### Servers

`Servers` recorder 擷取運行應用程式的伺服器的 CPU、記憶體、儲存用量。
使用此 recorder 需在各監控對象伺服器上持續啟動 `pulse:check` 指令。

```shell theme={null}
php artisan pulse:check
```

伺服器名稱預設使用 PHP 的 `gethostname()` 值。可設定環境變數自訂。

```ini theme={null}
PULSE_SERVER_NAME=load-balancer
```

### Users

`UserRequests` 與 `UserJobs` recorder 會擷取發送請求或 job 的使用者資訊，並顯示在「Application Usage」卡片中。

### Redis Ingest

在高流量環境中，可先將 entry 傳送到 Redis stream，再匯入資料庫。

```ini theme={null}
PULSE_INGEST_DRIVER=redis
```

使用 Redis ingest 時，需以 `pulse:work` 指令監聽 stream。

```shell theme={null}
php artisan pulse:work
```

***

## 取樣

在高流量環境擷取全部事件時，資料庫可能會累積數百萬列。
啟用**取樣**後，只會記錄部分事件，並在儀表板以近似值顯示。

```php theme={null}
// config/pulse.php
Recorders\UserRequests::class => [
    'sample_rate' => 0.1, // 只記錄 10% 的請求
],
```

儀表板中會在近似值前顯示 `~`。
指標的 entry 越多，越能維持精度並降低取樣率。

***

## 環境變數

主要設定可透過環境變數控制。

| 環境變數                            | 說明                       | 預設                 |
| ------------------------------- | ------------------------ | ------------------ |
| `PULSE_ENABLED`                 | Pulse 啟用／停用              | `true`             |
| `PULSE_DB_CONNECTION`           | Pulse 使用的 DB 連線          | 應用預設               |
| `PULSE_INGEST_DRIVER`           | Ingest driver（如 `redis`） | `storage`          |
| `PULSE_SERVER_NAME`             | 伺服器識別名稱                  | `gethostname()` 的值 |
| `PULSE_SLOW_REQUESTS_THRESHOLD` | 慢速請求門檻（ms）               | `1000`             |
| `PULSE_SLOW_JOBS_THRESHOLD`     | 慢速 job 門檻（ms）            | `1000`             |
| `PULSE_SLOW_QUERIES_THRESHOLD`  | 慢速查詢門檻（ms）               | `1000`             |

***

## 自訂卡片

可建立自訂的 Pulse 卡片，顯示應用程式特有的資料。
卡片以 [Livewire](https://livewire.laravel.com/) 元件實作。

```php theme={null}
namespace App\Livewire\Pulse;

use Laravel\Pulse\Livewire\Card;
use Livewire\Attributes\Lazy;

#[Lazy]
class TopSellers extends Card
{
    public function render()
    {
        return view('livewire.pulse.top-sellers');
    }
}
```

在卡片的 view 中，可以使用 Pulse 提供的 Blade 元件實現一致的視覺呈現。

```blade theme={null}
<x-pulse::card :cols="$cols" :rows="$rows" :class="$class" wire:poll.5s="">
    <x-pulse::card-header name="Top Sellers">
        <x-slot:icon>
            ...
        </x-slot:icon>
    </x-pulse::card-header>

    <x-pulse::scroll :expand="$expand">
        ...
    </x-pulse::scroll>
</x-pulse::card>
```

自訂資料的擷取可使用 `Pulse::record` 方法。

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

Pulse::record('user_sale', $user->id, $sale->amount)
    ->sum()
    ->count();
```

將建立的元件放進儀表板 view。

```blade theme={null}
<x-pulse>
    ...
    <livewire:pulse.top-sellers cols="4" />
</x-pulse>
```

***

## 總結

| 需求          | 方法                               |
| ----------- | -------------------------------- |
| 安裝 Pulse    | `composer require laravel/pulse` |
| 存取儀表板       | `/pulse` 路由                      |
| 在正式環境進行存取控制 | 定義 `viewPulse` gate              |
| 啟用伺服器監控     | 持續啟動 `php artisan pulse:check`   |
| 設定取樣        | 以 `sample_rate` 選項指定比率           |

## 後續步驟

<Columns cols={2}>
  <Card title="錯誤處理" icon="circle-x" href="/zh-TW/error-handling">
    了解應用程式的例外處理與回報機制。
  </Card>

  <Card title="Logging" icon="file-text" href="/zh-TW/logging">
    說明 Laravel 記錄系統的設定與活用方式。
  </Card>
</Columns>


## Related topics

- [Laravel Reverb](/zh-TW/reverb.md)
- [Laravel Telescope](/zh-TW/telescope.md)
- [Laravel Pennant](/zh-TW/pennant.md)
- [Laravel Telescope 實戰技巧](/zh-TW/blog/telescope-introduction.md)
- [Laravel Nightwatch 入門](/zh-TW/blog/nightwatch-introduction.md)
