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

Statamic Health Laravel Package

spatie/statamic-health

Statamic addon that integrates Spatie Laravel Health to monitor your app with configurable checks (e.g., disk space). View health status in the control panel and get notifications via mail or Slack when checks warn or fail.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/statamic-health
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="Spatie\Health\HealthServiceProvider"
    
  2. First Check: Register a basic check in a service provider (e.g., AppServiceProvider):

    use Spatie\Health\Facades\Health;
    use Spatie\Health\Checks\Checks\DatabaseConnectionCheck;
    
    Health::checks([
        DatabaseConnectionCheck::new(),
    ]);
    
  3. Trigger Health Check: Run the health check via CLI:

    php artisan health:check
    

    Or access the web endpoint (if configured):

    php artisan health:check --web
    
  4. View Results: Output will display status (pass/fail/warn) for each check. Example:

    ✅ Database Connection: OK
    ⚠️ Disk Space: 85% used (warning threshold: 70%)
    

First Use Case: Monitoring Critical Systems

Use the package to verify core dependencies like:

  • Database connectivity (DatabaseConnectionCheck)
  • Queue workers (QueueWorkerCheck)
  • External API availability (UrlCheck)

Example:

Health::checks([
    DatabaseConnectionCheck::new(),
    UrlCheck::new()
        ->url('https://api.example.com/health')
        ->failIfStatusCodeIsNot(200),
]);

Implementation Patterns

Workflows

  1. Registration:

    • Register checks in AppServiceProvider@boot() or a dedicated HealthServiceProvider.
    • Group related checks (e.g., all database-related checks together).
  2. Configuration:

    • Use fluent methods to set thresholds (e.g., warnWhenUsedSpaceIsAbovePercentage(70)).
    • Override defaults via config (config/health.php).
  3. Execution:

    • CLI: Run php artisan health:check in CI/CD pipelines or cron jobs.
    • Web: Expose results via HTTP endpoint (configured in config/health.php):
      'web' => [
          'enabled' => true,
          'path' => 'health',
      ],
      
      Access at /health (protected by middleware if needed).
  4. Notifications:

    • Integrate with Laravel Notifications to alert on failures/warnings:
      Health::checks([
          UsedDiskSpaceCheck::new()
              ->warnWhenUsedSpaceIsAbovePercentage(70)
              ->failWhenUsedSpaceIsAbovePercentage(90)
              ->notifyOnFailure(),
      ]);
      

Integration Tips

  1. Statamic-Specific Checks:

    • Extend Check class to monitor Statamic components:
      use Spatie\Health\Checks\Check;
      
      class StatamicCacheCheck extends Check
      {
          public function run(): array
          {
              return [
                  'status' => Statamic::cache()->has('key') ? 'ok' : 'missing',
              ];
          }
      }
      
  2. Conditional Checks:

    • Skip checks in specific environments:
      if (app()->environment('production')) {
          Health::checks([UsedDiskSpaceCheck::new()]);
      }
      
  3. Custom Thresholds:

    • Dynamically set thresholds based on environment variables:
      $threshold = config('health.disk_warn_threshold', 70);
      Health::checks([
          UsedDiskSpaceCheck::new()->warnWhenUsedSpaceIsAbovePercentage($threshold),
      ]);
      
  4. Performance:

    • Run checks in parallel (if supported) by leveraging Laravel’s parallel helper or queue jobs.

Gotchas and Tips

Pitfalls

  1. Missing Config:

    • Forgetting to publish the config (php artisan vendor:publish) may lead to undefined settings.
    • Fix: Always publish and review config/health.php.
  2. Overlapping Checks:

    • Registering duplicate checks (e.g., two DatabaseConnectionCheck instances) can cause redundant notifications.
    • Fix: Use a single registration point (e.g., AppServiceProvider).
  3. Web Endpoint Security:

    • The web endpoint (/health) may expose sensitive data if not protected.
    • Fix: Add middleware to restrict access:
      Route::middleware(['auth:sanctum'])->get('/health', [HealthCheckController::class, 'index']);
      
  4. False Positives:

    • Checks like UsedDiskSpaceCheck may trigger warnings during deployments (e.g., temporary high usage).
    • Fix: Adjust thresholds or skip checks during deployments:
      if (!app()->runningInConsole() || !app()->isDownForMaintenance()) {
          Health::checks([UsedDiskSpaceCheck::new()]);
      }
      

Debugging

  1. Check Output:

    • Use --verbose flag for detailed logs:
      php artisan health:check --verbose
      
  2. Isolate Issues:

    • Temporarily disable all checks except one to identify the source of failures:
      Health::checks([DatabaseConnectionCheck::new()]);
      
  3. Log Results:

    • Extend checks to log results to a file or monitoring system:
      class CustomCheck extends Check
      {
          protected function run(): array
          {
              $result = ['status' => 'ok'];
              Log::info('Custom check result', $result);
              return $result;
          }
      }
      

Tips

  1. Custom Checks:

    • Extend Spatie\Health\Checks\Check to create reusable checks:
      class RedisHealthCheck extends Check
      {
          public function run(): array
          {
              return [
                  'status' => Redis::ping() ? 'ok' : 'failed',
              ];
          }
      }
      
  2. Environment-Specific Checks:

    • Use app()->environment() to enable checks only in specific environments:
      if (app()->environment(['staging', 'production'])) {
          Health::checks([QueueWorkerCheck::new()]);
      }
      
  3. Notification Channels:

    • Configure notifications in config/health.php:
      'notifications' => [
          'mail' => true,
          'slack' => [
              'enabled' => true,
              'webhook_url' => env('SLACK_WEBHOOK_URL'),
          ],
      ],
      
  4. Documentation:

    • Add a README.md in your project to document custom checks and their thresholds for future developers.
  5. Testing:

    • Mock checks in unit tests to verify behavior:
      $check = new DatabaseConnectionCheck();
      $this->assertEquals('ok', $check->run()['status']);
      
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