> ## 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](/ko/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의 1st-party 스토리지 구현은 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` 인증 게이트를 커스터마이즈하여 접근 제어를 설정해 주세요.

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

***

## 레코더

레코더는 애플리케이션의 이벤트를 캡처해 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 스트림에 송신한 후 데이터베이스에 가져오는 방법을 이용할 수 있습니다.

```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가 사용하는 DB 커넥션    | 앱의 기본값             |
| `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` 게이트 정의               |
| 서버 모니터링 활성화     | `php artisan pulse:check`를 상시 기동 |
| 샘플링 설정          | `sample_rate` 옵션으로 비율 지정         |

## 다음 단계

<Columns cols={2}>
  <Card title="에러 핸들링" icon="circle-x" href="/ko/error-handling">
    애플리케이션의 예외 처리와 리포트의 구조를 배웁니다.
  </Card>

  <Card title="로깅" icon="file-text" href="/ko/logging">
    Laravel의 로그 시스템의 설정과 활용 방법을 설명합니다.
  </Card>
</Columns>


## Related topics

- [Laravel Reverb](/ko/reverb.md)
- [Laravel Telescope](/ko/telescope.md)
- [Laravel Pennant](/ko/pennant.md)
- [Laravel Telescope 실전 테크닉](/ko/blog/telescope-introduction.md)
- [Laravel Nightwatch 입문](/ko/blog/nightwatch-introduction.md)
