> ## 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 应用监控仪表盘的安装与配置。涵盖记录器、采样以及自定义卡片的实现。

## 什么是 Laravel Pulse

[Laravel Pulse](https://github.com/laravel/pulse) 是一个能一眼掌握应用性能与使用情况的监控仪表盘。
你可以用它定位慢任务、慢接口等瓶颈，也可以了解最活跃的用户。

### Telescope 与 Pulse 的区别

| 特点   | Laravel Pulse  | Laravel Telescope |
| ---- | -------------- | ----------------- |
| 目的   | 监控应用整体的趋势与聚合数据 | 逐个请求 / 事件的深度调试    |
| 数据   | 已聚合的指标         | 单条事件日志            |
| 适用场景 | 生产环境的性能监控      | 开发 / 预发环境调试       |

<Info>
  需要针对单个事件深度调试时，请使用 [Laravel Telescope](/zh/blog/telescope-introduction)。
</Info>

### 数据流图

```mermaid theme={null}
flowchart LR
    A["Laravel 应用"] -->|检测事件| B["记录器<br>(Recorders)"]
    B -->|写入条目| C["数据库<br>(Pulse 表)"]
    C -->|聚合展示| D["仪表盘<br>/pulse"]
    E["pulse:check<br>守护进程"] -->|服务器信息| C
```

***

## 安装

<Warning>
  Pulse 的官方存储实现需要 MySQL、MariaDB 或 PostgreSQL。如果你使用其他数据库引擎，请为 Pulse 数据单独准备一个 MySQL、MariaDB 或 PostgreSQL 数据库。
</Warning>

<Steps>
  <Step title="安装扩展包">
    使用 Composer 安装 Pulse。

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

  <Step title="发布配置文件与迁移">
    通过 `vendor:publish` Artisan 命令发布文件。

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

  <Step title="执行迁移">
    创建用于保存 Pulse 数据的表。

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

迁移完成后，就可以通过 `/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` 方法。

### 仪表盘的自定义

可以发布仪表盘视图，自定义卡片和布局。

```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 />
```

***

## 记录器（Recorders）

记录器负责捕获应用的事件并写入 Pulse 数据库。
配置位于 `config/pulse.php` 的 `recorders` 部分。

### Requests / Slow Requests

`Requests` 记录器会捕获对应用的请求信息。
可以设置慢路由的阈值（默认 1000ms）、采样率以及需要忽略的路径。

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

### Slow Jobs

`SlowJobs` 记录器会捕获超出阈值的慢任务（默认 1000ms）。
可以为不同任务设置不同的阈值。

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

### Exceptions

`Exceptions` 记录器会捕获应用中可上报的异常，并按异常类和发生位置分组。

### Cache

`CacheInteractions` 记录器会捕获缓存命中与未命中，也可以用正则把类似的键分组。

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

### Queues

`Queues` 记录器会捕获队列中任务的吞吐量（排队、处理中、已完成、释放、失败）。

### Servers

`Servers` 记录器会捕获运行应用的服务器的 CPU、内存与磁盘使用情况。
使用该记录器需要在每台被监控的服务器上保持 `pulse:check` 命令常驻运行。

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

服务器名默认使用 PHP `gethostname()` 的返回值。要自定义可以设置环境变量。

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

### Users

`UserRequests` 与 `UserJobs` 记录器会捕获发起请求或任务的用户信息，展示在 “Application Usage” 卡片中。

### Redis Ingest

在高流量环境下，可以先把条目发送到 Redis 流，再由 Pulse 从流中读取写入数据库。

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

使用 Redis 摄取时需要用 `pulse:work` 命令监听流。

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

***

## 采样

高流量场景下，如果记录所有事件，数据库中可能会积累数百万行。
启用**采样**后，只会记录部分事件，仪表盘会以近似值显示。

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

近似值前会显示 `~`。
指标条目数越多，即使降低采样率也能保持较高的精度。

***

## 环境变量

主要配置可以通过环境变量控制。

| 环境变量                            | 说明              | 默认值                |
| ------------------------------- | --------------- | ------------------ |
| `PULSE_ENABLED`                 | 启用/禁用 Pulse     | `true`             |
| `PULSE_DB_CONNECTION`           | Pulse 使用的数据库连接  | 应用默认               |
| `PULSE_INGEST_DRIVER`           | 摄取驱动（如 `redis`） | `storage`          |
| `PULSE_SERVER_NAME`             | 服务器标识名          | `gethostname()` 的值 |
| `PULSE_SLOW_REQUESTS_THRESHOLD` | 慢请求阈值（ms）       | `1000`             |
| `PULSE_SLOW_JOBS_THRESHOLD`     | 慢任务阈值（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');
    }
}
```

在卡片视图中，可以使用 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();
```

创建好的组件可以嵌入到仪表盘视图中。

```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/error-handling">
    了解应用的异常处理与上报机制。
  </Card>

  <Card title="日志" icon="file-text" href="/zh/logging">
    介绍 Laravel 日志系统的配置与使用方式。
  </Card>
</Columns>


## Related topics

- [Laravel Reverb](/zh/reverb.md)
- [Laravel Pennant](/zh/pennant.md)
- [Laravel Telescope](/zh/telescope.md)
- [Laravel Telescope 实战技巧](/zh/blog/telescope-introduction.md)
- [Laravel Nightwatch 入门](/zh/blog/nightwatch-introduction.md)
