NovinkaZverejnili sme 50+ Laravel balíkov ako open source
Custom AI apps, agents and automation — Roundly ConsultingRoundly
Všetky balíky
Alerts for Laravel

Vlastné kontroly

Rozšírte RoundlyConsulting\Alerts\Check a implementujte check() a notification():

use Illuminate\Notifications\Notification;
use RoundlyConsulting\Alerts\Check;
use RoundlyConsulting\Alerts\CheckResult;

class DiskUsageCheck extends Check
{
    public function check(): CheckResult
    {
        // $this->healthCheck holds the scheduled HealthCheck record and its meta.
        $serverId = $this->healthCheck?->meta['server_id'] ?? null;

        return CheckResult::ok(
            message: 'Disk usage within limits',
            meta: ['server_id' => $serverId],
        );

        // Return CheckResult::failed('Disk almost full', [...]) to trigger an alert.
    }

    public function notification(object $notifiable): Notification
    {
        return new DiskUsageNotification();
    }
}

$this->healthCheck je naplánovaný riadok HealthCheck, pre ktorý kontrola beží, aj s jeho meta. Keď kontrola beží bez riadka — napríklad alerts:check bez --notifiable — je null, preto ho čítajte null-safe.

Úplnejší príklad

Prepíšte name(), key(), description() alebo tags(), ak chcete zmeniť, ako sa kontrola prezentuje. Tu deklarované tagy sa zlúčia s tagmi každého riadka. Použite pribalenú notifikáciu a odovzdajte jej $this->channels(), aby platilo notifyVia():

use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Http;
use RoundlyConsulting\Alerts\Check;
use RoundlyConsulting\Alerts\CheckResult;
use RoundlyConsulting\Alerts\Notifications\HealthCheckFailedNotification;

class PaymentGatewayCheck extends Check
{
    public function name(): string
    {
        return 'Payment gateway';
    }

    public function tags(): array
    {
        return ['critical', 'billing'];
    }

    public function check(): CheckResult
    {
        $url = $this->healthCheck?->meta['url'] ?? 'https://payments.example.com/status';

        // No try/catch needed — a thrown exception becomes a failed result.
        $response = Http::timeout(5)->get($url);

        return $response->successful()
            ? CheckResult::ok('Gateway reachable', ['url' => $url])
            : CheckResult::failed('Gateway returned '.$response->status(), ['url' => $url]);
    }

    public function notification(object $notifiable): Notification
    {
        // Reuse the bundled notification and honour notifyVia() routing.
        return new HealthCheckFailedNotification($this, channels: $this->channels());
    }
}

Keďže každý riadok nesie vlastné meta, jedna trieda kontroly môže pre toho istého vlastníka sledovať viacero služieb. Každý riadok má vlastné počítadlá, alerty aj obmedzenie notifikácií:

// One check class, two monitors — each row carries its own target in meta.
Health::for($team)->monitor(PaymentGatewayCheck::class)
    ->everyMinute()
    ->meta(['url' => 'https://payments.example.com/status'])
    ->save();

Health::for($team)->monitor(PaymentGatewayCheck::class)
    ->everyMinute()
    ->meta(['url' => 'https://payouts.example.com/status'])
    ->save();

Pri registrácii alebo plánovaní podľa názvu triedy sa kontroly vytvárajú bez argumentov konštruktora. Konfiguráciu preto držte vo fluentných setteroch registrovanej inštancie alebo v meta riadka.

Výsledky a závažnosť

CheckResult nesie Status — ok, warning, failed alebo skipped — a k nemu správu a pole meta:

use RoundlyConsulting\Alerts\CheckResult;

CheckResult::ok();
CheckResult::warning('Disk filling up');
CheckResult::failed('Disk full');
CheckResult::skipped('Maintenance window');
StavZávažnosťÚčinok behu
ok0Vynuluje počítadlo zlyhaní a počíta sa do obnovy otvoreného alertu.
skipped1Zaznamená beh a nič viac — žiadne počítadlá, alert ani notifikácia.
warning2Počíta sa ako zlyhanie: otvorí alert a upozorní, rovnako ako failed.
failed3Počíta sa ako zlyhanie: otvorí alert a upozorní.
use RoundlyConsulting\Alerts\CheckResult;
use RoundlyConsulting\Alerts\Enums\Status;

$result = CheckResult::failed('Disk full', ['free_bytes' => 1024]);

$result->status;   // Status::Failed
$result->message;  // 'Disk full'
$result->meta;     // ['free_bytes' => 1024]
$result->isOk;     // false — legacy flag, true only for Status::Ok

new CheckResult(true);                     // same as CheckResult::ok()
new CheckResult(false, 'Down');            // same as CheckResult::failed('Down')
new CheckResult(Status::Warning, 'Slow');  // any Status works too

V check() nikdy nepotrebujete try/catch: vyhodená výnimka sa automaticky zmení na výsledok failed (pozri Časové limity a chyby).

Enum Status

Status si ponecháva doménové metódy isAlertable() a severity() a používa trait Helpers z enums-for-laravel, takže je pripravený pre výberové polia, validačné pravidlá aj API odpovede:

use RoundlyConsulting\Alerts\Enums\Status;

Status::Warning->isAlertable();  // true — opens an alert and notifies
Status::Failed->severity();      // 3 (ok 0, skipped 1, warning 2, failed 3)

Status::values();                // Collection: ok, warning, failed, skipped
Status::toOptions();             // Collection: 'ok' => 'Ok', 'warning' => 'Warning', …
Status::validationRule();        // 'in:ok,warning,failed,skipped'
Status::Failed->label();         // 'Failed'
Status::tryFromLabel('Warning'); // Status::Warning

K dispozícii sú aj names(), labels(), options(), readable(), fromName()/tryFromName(), fromLabel(), hasValue(), is()/isIn() a podmienky when*.

Prejavte lásku k open source

Tento balík je zadarmo pod licenciou MIT. Ak vám šetrí čas, jednorazový príspevok alebo členstvo na Patreone nám pomôže ho ďalej udržiavať, testovať a dokumentovať.

Ďalšie spôsoby podpory vrátane kryptomien

Odoslaním daru súhlasíte s našimi podmienkami prijímania darov.

Chcete to zabudovať do svojho produktu?

Naše balíky integrujeme do zákazkových Laravel a AI riešení. Napíšte nám, na čom pracujete, a ozveme sa do 48 hodín.