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

# Custom Pulse Recorders in Packages

> Learn how to use Laravel Pulse recorders to aggregate package-specific events on the dashboard. This covers subscribing with listen, aggregating with Pulse::record, configuring ignore and sample_rate, and exception handling.

Laravel Pulse aggregates requests, queries, jobs and more on the dashboard. When your package does its own work, a custom recorder lets you monitor the count and duration of that work in Pulse.

This guide builds a recorder that subscribes to an event dispatched by a package and records its count and duration. For basic Pulse usage, see [Pulse](https://kawax.biz/en/pulse.md).

> [!NOTE]
>
> This guide is based on the source code of Pulse 1.11.0. The `ReportGenerated` event in the examples is a hypothetical class for illustration. In a real package, replace it with your own event.

## How It Works

When a recorder receives an event, it adds records to Pulse's buffer. The buffer is saved in batches at ingest time.

```mermaid theme={null}
flowchart LR
    A["Event dispatched"] --> B["listen calls<br>record"]
    B --> C["Pulse::record<br>creates an Entry"]
    C --> D["Pulse buffer"]
    D --> E["Saved on ingest"]
    E --> F["pulse_entries"]
    E --> G["pulse_aggregates"]
    F --> H["Shown on dashboard"]
    G --> H
```

## Create a Recorder

A recorder declares the events to subscribe to in the `listen` property and implements the work in the `record()` method. The example below records the `ReportGenerated` event that a package dispatches. The event is assumed to have `$type` and `$durationMs` properties.

```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();
    }
}
```

The `Ignores` and `Sampling` traits read the `ignore` and `sample_rate` settings described below.

## Register the Recorder in the Application

Register the recorder in the `recorders` array of the application's `config/pulse.php`. Use the recorder's class name as the key, and specify the enable flag and settings as the value.

```php theme={null}
'recorders' => [
    // Keep the existing recorders as they are
    Acme\Reports\Pulse\ReportGenerationRecorder::class => [
        'enabled' => true,
        'sample_rate' => 1,
        'ignore' => ['/^debug_/'],
    ],
],
```

`PulseServiceProvider` loads `pulse.recorders` and registers the recorders when `pulse.enabled` is on. A recorder with `enabled` set to `false` is not registered. Rather than rewriting this setting automatically from the package, it is safer to show the configuration example in the installation instructions.

## Aggregate Types

`Pulse::record()` returns an `Entry`. Chaining `count()`, `min()`, `max()`, `sum()` or `avg()` stores the matching aggregate in `pulse_aggregates`.

| Method | Stored value |
| - | - |
| `count()` | Count |
| `min()` | Minimum value |
| `max()` | Maximum value |
| `sum()` | Sum |
| `avg()` | Average |
| `onlyBuckets()` | Saves only the aggregate results, without individual records in `pulse_entries` |

`min()`, `max()`, `sum()` and `avg()` use `value` in their calculation. `count()` alone does not need a `value`.

When an event fires very frequently, `onlyBuckets()` reduces the number of rows in `pulse_entries`.

## Store a String Value

When you want to store a string, such as the latest state, rather than aggregate a number, use `Pulse::set()`. The value is saved in the `pulse_values` table.

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

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

The `value` must be passed as a `string`.

## Defer Expensive Work

The closure passed to `Pulse::lazy()` does not run immediately. It runs when Pulse ingests the data. Use it when recording takes time and you want it to run after the response is sent.

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

## Record the Authenticated User

When you need the identifier of the authenticated user, use `Pulse::resolveAuthenticatedUserId()`. It returns `null` when no user is authenticated.

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

## Ignore, Sample and Filter

Use these four tools to reduce what gets recorded:

* `ignore` setting: Skips recording when the value passed to `shouldIgnore()` matches one of the regular expressions. In the example above, events whose `$event->type` matches `/^debug_/` are skipped.
* `sample_rate` setting: Checked by `shouldSample()`. `1` records every event, and `0.1` records about 10%.
* `Pulse::ignore()`: Disables recording inside the callback and returns the callback's result.
* `Pulse::filter()`: Receives each `Entry` or `Value` before it is stored and saves only the items for which it returns `true`.

## Exception Handling

Pulse wraps recorder work and ingestion in `rescue()`. Exceptions thrown inside a recorder do not reach your application. If `handleExceptionsUsing()` is not set, the exception is silently discarded. To report exceptions, configure this in your application.

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

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

## Testing

To test a recorder, you can dispatch the event, call `Pulse::ingest()`, and check the saved row. The example below is derived from the Pulse source and has not been run. Make sure `pulse.enabled` is on in your test environment.

```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,
    ]);
});
```

## Designing Keys

`key` is the unit of aggregation. If you use values that grow without limit, such as user IDs or URLs, the data volume grows and the aggregates become hard to read. Use values with a limited set, such as event types or process names, for `key`.


## Related topics

- [Advanced Topics](https://kawax.biz/en/advanced/index.md)
- [Laravel Pulse](https://kawax.biz/en/pulse.md)
- [Custom session drivers in packages](https://kawax.biz/en/advanced/package-session-drivers.md)
- [Custom UserProviders in Packages](https://kawax.biz/en/advanced/package-user-providers.md)
- [Core package and custom drivers - Feedable](https://kawax.biz/en/packages/feedable/core.md)


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