Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Health Laravel Package

spatie/laravel-health

Monitor your Laravel app’s health by registering checks (disk space, etc.) with warning/fail thresholds. Get notified via mail or Slack when checks degrade, and extend with custom checks for proactive alerting.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require spatie/laravel-health
    php artisan vendor:publish --tag="health-config"
    php artisan vendor:publish --tag="health-migrations"
    php artisan migrate
    
  2. Register a Basic Check (e.g., disk space):

    // In a Service Provider (e.g., AppServiceProvider.php)
    use Spatie\Health\Facades\Health;
    use Spatie\Health\Checks\Checks\UsedDiskSpaceCheck;
    
    Health::checks([
        UsedDiskSpaceCheck::new()
            ->warnWhenUsedSpaceIsAbovePercentage(70)
            ->failWhenUsedSpaceIsAbovePercentage(90),
    ]);
    
  3. Schedule Checks (in app/Console/Kernel.php):

    use Illuminate\Support\Facades\Schedule;
    use Spatie\Health\Commands\RunHealthChecksCommand;
    
    protected function schedule(Schedule $schedule)
    {
        $schedule->command(RunHealthChecksCommand::class)->everyMinute();
    }
    
  4. Verify Setup:

    • Access the web dashboard at /health (default route).
    • Check logs for notifications (if configured).

Implementation Patterns

Core Workflows

  1. Check Registration:

    • Built-in Checks: Use pre-defined checks (e.g., DatabaseConnectionCheck, QueueCheck).
      Health::checks([
          new DatabaseConnectionCheck(),
          new QueueCheck(),
      ]);
      
    • Custom Checks: Extend Check class or use closures:
      Health::checks([
          new class extends Check {
              public function run(): Result {
                  return Result::ok('Custom check passed');
              }
          },
      ]);
      
  2. Result Handling:

    • Statuses: Checks return Result with ok(), warn(), or fail().
    • Thresholds: Configure warnings/failures (e.g., CPU usage):
      Health::checks([
          new CpuUsageCheck()
              ->warnWhenAbovePercentage(80)
              ->failWhenAbovePercentage(95),
      ]);
      
  3. Notification Integration:

    • Mail/Slack: Configure in config/health.php:
      'notifications' => [
          'enabled' => true,
          'notifications' => [
              \Spatie\Health\Notifications\CheckFailedNotification::class => ['mail', 'slack'],
          ],
          'mail' => ['to' => 'admin@example.com'],
          'slack' => ['webhook_url' => env('SLACK_WEBHOOK')],
      ],
      
    • Oh Dear: For external monitoring (see Oh Dear docs).
  4. Result Storage:

    • Database: Default (EloquentHealthResultStore).
    • Alternatives: Cache, JSON files, or in-memory (for testing):
      'result_stores' => [
          \Spatie\Health\ResultStores\InMemoryHealthResultStore::class,
      ],
      
  5. API Endpoints:

    • JSON Endpoint: Fetch results via /health.json?fresh=true.
    • Web Dashboard: Access at /health (customizable theme: light/dark).

Integration Tips

  1. Environment-Specific Checks:

    • Dynamically register checks based on environment (e.g., disable QueueCheck in testing):
      if (app()->environment('production')) {
          Health::checks([new QueueCheck()]);
      }
      
  2. Dependency Checks:

    • Verify external services (e.g., payment gateways):
      Health::checks([
          new class extends Check {
              public function run(): Result {
                  return Http::get('https://api.stripe.com')->successful()
                      ? Result::ok('Stripe API is reachable')
                      : Result::fail('Stripe API unavailable');
              }
          },
      ]);
      
  3. Custom Notifiables:

    • Extend Notifiable to send alerts to specific users/teams:
      class TeamNotifiable extends \Spatie\Health\Notifications\Notifiable {
          public function routeNotificationForMail(): array {
              return ['admin@team.com'];
          }
      }
      
      Then update config/health.php:
      'notifiable' => \App\Notifications\TeamNotifiable::class,
      
  4. Queue-Based Checks:

    • Offload checks to queues for long-running tasks:
      Health::checks([
          new class extends Check {
              public function run(): Result {
                  return (new HealthQueueJob($this))->dispatch()->wasSuccessful()
                      ? Result::ok()
                      : Result::fail();
              }
          },
      ]);
      
  5. Local Development:

    • Use InMemoryHealthResultStore to avoid cluttering the DB:
      'result_stores' => [
          \Spatie\Health\ResultStores\InMemoryHealthResultStore::class,
      ],
      

Gotchas and Tips

Pitfalls

  1. Notification Spam:

    • Issue: Frequent failures trigger rapid notifications.
    • Fix: Adjust throttle_notifications_for_minutes in config/health.php (default: 60 minutes).
    • Example:
      'throttle_notifications_for_minutes' => 120, // 2 hours
      
  2. Database Locks:

    • Issue: Concurrent RunHealthChecksCommand executions may cause deadlocks.
    • Fix: Use lockFor() in the command or limit scheduling frequency (e.g., every 2 minutes).
  3. Secret Leaks:

    • Issue: Hardcoding OH_DEAR_HEALTH_CHECK_SECRET in config.
    • Fix: Always use .env:
      OH_DEAR_HEALTH_CHECK_SECRET=your_secure_secret_here
      
  4. Missing Migrations:

    • Issue: Forgetting to run migrations after publishing.
    • Fix: Add to deployment script:
      php artisan vendor:publish --tag="health-migrations" --force
      php artisan migrate --force
      
  5. Oh Dear Timeouts:

    • Issue: Slow checks cause Oh Dear to timeout.
    • Fix: Disable always_send_fresh_results or optimize checks:
      'oh_dear_endpoint' => [
          'always_send_fresh_results' => false,
      ],
      

Debugging Tips

  1. Check Logs:

    • Inspect storage/logs/laravel.log for check execution errors.
    • Enable debug mode in config/health.php (if available in future versions).
  2. Manual Check Execution:

    • Test checks without scheduling:
      php artisan health:checks
      
  3. Result Inspection:

    • Dump results for debugging:
      $results = Health::checks();
      dd($results->all());
      
  4. Slack/Mail Debugging:

    • Verify notification channels:
      php artisan queue:work --once  # Check for failed jobs
      php artisan queue:failed-table  # Inspect failed notifications
      
  5. Oh Dear Verification:

    • Test the endpoint manually:
      curl -X GET "http://your-app.test/oh-dear-health-check-results?secret=your_secret"
      

Extension Points

  1. Custom Check Logic:

    • Extend Check class to add logic (e.g., API rate limits):
      class ApiRateLimitCheck extends Check {
          public function run(): Result {
              $limit = Http::get('https://api.example.com/limits')->json();
              return $limit['remaining'] > 10
                  ? Result::ok("API calls remaining: {$limit['remaining']}")
                  : Result::fail("Low API calls remaining: {$limit['remaining']}");
          }
      }
      
  2. Result Storage Extensions:

    • Create a custom store (e.g., Elasticsearch):
      class ElasticsearchHealthResultStore implements ResultStore {
          public function store(HealthCheckResult $result): void {
              // Custom logic to index results
          }
      }
      
      Register in config/health.php:
      'result_stores' => [
          \App\ResultStores\ElasticsearchHealthResultStore::class,
      ],
      
  3. Notification Channels:

    • Add support for new channels (e.g., PagerDuty):
      class PagerDutyNotification extends Notification {
          public function via($notifiable) {
              return ['pagerduty'];
          }
      }
      
      Register in config/health.php:
      'notifications' => [
          'notifications' => [
              \App\Notifications\PagerDutyNotification::class => ['p
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport