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

Server Monitor App Laravel Package

spatie/server-monitor-app

Laravel-based command-line app to monitor your servers’ health (disk, memory, processes, etc.) with built-in checks and alerts via Slack or email. Powered by Spatie’s laravel-server-monitor; ideal if you want a ready-to-run monitoring app.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer create-project spatie/server-monitor-app
    

    Clone the repo and run composer install.

  2. Configuration:

    • Copy .env.example to .env and update database credentials (MySQL/PostgreSQL/SQLite).
    • Run migrations:
      php artisan migrate
      
    • Configure checks in .env (e.g., CHECK_DISK_SPACE=true, CHECK_PROCESSES=true).
  3. First Run:

    • Schedule a cron job to run checks periodically (e.g., every 5 minutes):
      * * * * * cd /path/to/server-monitor-app && php artisan schedule:run >> /dev/null 2>&1
      
    • Access the dashboard at http://localhost:8000 (serve with php artisan serve for testing).
  4. Notifications:

    • Configure Slack/Mail in .env (e.g., SLACK_WEBHOOK_URL, MAIL_MAILER).
    • Enable notifications for checks in config/server-monitor.php.

First Use Case: Monitoring Disk Space

  1. Enable the disk space check in .env:
    CHECK_DISK_SPACE=true
    DISK_SPACE_CHECK_THRESHOLD=10
    
  2. Define thresholds for /, /var, etc., in config/server-monitor.php.
  3. Trigger a manual check:
    php artisan server-monitor:check
    
  4. Verify alerts in the dashboard or Slack.

Implementation Patterns

Workflows

  1. Check Creation:

    • Extend built-in checks by creating custom checks in app/Checks.
    • Example: A custom CheckRedisMemory.php:
      namespace App\Checks;
      
      use Spatie\ServerMonitor\Checks\Check;
      
      class CheckRedisMemory extends Check
      {
          public function getName(): string
          {
              return 'Redis Memory Usage';
          }
      
          public function check(): array
          {
              $memory = shell_exec('redis-cli info memory | grep used_memory');
              return ['memory_used' => $memory];
          }
      
          public function isOk(): bool
          {
              return (int) $this->memoryUsed < 100000000; // 100MB threshold
          }
      }
      
    • Register the check in config/server-monitor.php under custom_checks.
  2. Notification Routing:

    • Use events to customize notifications. Example in EventServiceProvider:
      protected $listen = [
          \Spatie\ServerMonitor\Events\CheckFailed::class => [
              \App\Listeners\SendCustomSlackAlert::class,
          ],
      ];
      
    • Create a listener (app/Listeners/SendCustomSlackAlert.php) to modify payloads.
  3. Dashboard Customization:

    • Override views in resources/views/vendor/server-monitor.
    • Extend the dashboard layout by publishing assets:
      php artisan vendor:publish --tag=server-monitor-assets
      
  4. Multi-Server Monitoring:

    • Deploy the app on each server with unique .env configurations.
    • Use a central database (e.g., PostgreSQL) for cross-server visibility.
    • Aggregate alerts via a shared Slack channel or email.

Integration Tips

  1. Laravel Integration:

    • Use laravel-server-monitor directly in your Laravel app for tighter integration:
      composer require spatie/laravel-server-monitor
      
    • Share checks, notifications, and configurations between projects.
  2. CI/CD Hooks:

    • Trigger checks in deployment pipelines (e.g., GitHub Actions) to preemptively catch issues:
      - name: Run Server Checks
        run: php artisan server-monitor:check
      
  3. Logging:

    • Log check results to a centralized service (e.g., ELK Stack) for long-term analysis:
      use Monolog\Logger;
      
      $logger = new Logger('server_monitor');
      $logger->pushHandler(new \Monolog\Handler\SyslogHandler('server_monitor'));
      event(new \Spatie\ServerMonitor\Events\CheckFailed($check, $result));
      
  4. API Access:

    • Expose check results via a custom API endpoint:
      Route::get('/api/checks', function () {
          return \Spatie\ServerMonitor\Facades\ServerMonitor::checks()->latest()->take(10)->get();
      });
      

Gotchas and Tips

Pitfalls

  1. Cron Job Misconfiguration:

    • Ensure the cron job runs as the same user who owns the app files (permissions issues can break checks).
    • Test cron jobs manually:
      php artisan schedule:run
      
  2. Check Dependencies:

    • Some checks (e.g., CheckProcesses) require specific system tools (e.g., ps). Verify these are installed on all servers.
    • Use shell_exec cautiously—sanitize inputs to avoid command injection.
  3. Database Locks:

    • High-frequency checks may cause database locks. Optimize check intervals or use queue workers:
      php artisan queue:work
      
  4. Timezone Mismatches:

    • Ensure server timezones match the Laravel app’s timezone (configured in .env). Use date_default_timezone_set() in checks if needed.
  5. Notification Delays:

    • Slack/Mail notifications may fail silently. Implement retries or fallback notifications (e.g., SMS via Twilio).

Debugging

  1. Check Logs:

    • Enable debug mode in .env (APP_DEBUG=true) and check storage/logs/laravel.log.
    • Use php artisan server-monitor:check --verbose for detailed output.
  2. Test Checks Locally:

    • Mock system commands for local testing:
      $this->expectFacadeInstance(\Spatie\ServerMonitor\Facades\ServerMonitor::class)
           ->shouldReceive('executeCommand')
           ->andReturn('1000000'); // Simulate disk usage
      
  3. Database Issues:

    • Reset migrations if checks fail due to schema changes:
      php artisan migrate:fresh
      

Tips

  1. Custom Check Templates:

    • Use this template for new checks:
      namespace App\Checks;
      
      use Spatie\ServerMonitor\Checks\Check;
      
      class CustomCheck extends Check
      {
          public function getName(): string { return 'Custom Check'; }
      
          public function check(): array { return ['data' => 'value']; }
      
          public function isOk(): bool { return true; }
      
          public function getHelpText(): string { return 'Description of the check.'; }
      }
      
  2. Threshold Tuning:

    • Start with conservative thresholds (e.g., 20% disk space) and adjust based on historical data.
  3. Exclude Checks:

    • Disable checks temporarily in .env:
      CHECK_DISK_SPACE=false
      
  4. Backup Config:

    • Commit .env to version control (with sensitive values removed) for consistency across deployments.
  5. Monitor the Monitor:

    • Add a self-check to monitor the app’s uptime (e.g., a health endpoint):
      Route::get('/health', function () {
          return response()->json(['status' => 'ok']);
      });
      
    • Use CheckHttpEndpoint to verify this route periodically.
  6. Legacy Systems:

    • For older PHP versions, use the laravel-server-monitor package directly with a custom Laravel app (instead of this monolithic app).
  7. Documentation:

    • Refer to the official docs for advanced use cases (e.g., custom notifications, multi-server setups).
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