Laravel Health

repository·main·Indexed 21 days ago

https://github.com/spatie/laravel-health

A package to monitor Laravel application health by registering checks for disk space, database connectivity, CPU load, cache operations, and backup integrity. It supports custom warning and failure thresholds and can automatically trigger notifications via Mail or Slack.

Tokens
26.7K
Snippets
139
Records
153
Agent score
74%

What's inside spatie/laravel-health

  1. Overview of Laravel Health

    main
    Laravel Health is a package designed to monitor the health of your Laravel application by registering various health checks. It allows you to define thresholds for warnings and failures, and can automatically notify you via channels like Mail and Slack when your application's health status changes.
  2. Use third-party health check packages

    main

    In addition to the built-in checks, you can extend your application's monitoring capabilities using third-party health check packages. These are community-maintained packages designed to work with laravel-health.

    Examples of third-party checks include:

    • Domain Expiry Health Check
    • Env vars
    • SSL certificate expiration
    • Laravel Octane
    • Memory Usage Check
    • Queue Size Check
    • Opcache Check
  3. Available built-in health checks

    main

    The laravel-health package provides a variety of built-in checks to monitor different aspects of your application's infrastructure and configuration. You can register any of these checks to verify the health of your application.

    Built-in checks include:

    • Application & Environment: Application Cache, Debug Mode, Environment, Security advisories.
    • Infrastructure & Resources: CPU Load, Used Disk Space, Redis, Meilisearch.
    • Database: Database Connection, Database Connection Count, Database Table Size.
    • Laravel Ecosystem: Backups, Flare Error Count, Horizon, Queue, Schedule.
    • Connectivity: Ping.
  4. Configure a heartbeat URL for HorizonCheck

    main

    You can configure a heartbeat URL to be pinged automatically whenever the health checks run (via RunHealthChecksCommand) if the Horizon check passes. This is useful for external monitoring services like Oh Dear, Pingdom, or Envoyer.

    Note: The URL is only pinged if the check passes. The ping is independent of the check's status; the check might pass while the ping fails (e.g., due to a malformed URL).

    HORIZON_HEARTBEAT_URL=https://your-monitoring-service.com/ping/abc123
  5. Configure an Oh Dear health check endpoint

    main

    To prevent notification failures when your application is in a critical state, you can use Oh Dear to monitor your health checks. This requires registering a protected endpoint in your Laravel application that returns health check results as JSON.

    1. Publish the configuration file

    If you haven't already, publish the health configuration file:

    php artisan vendor:publish --tag="health-config"

    2. Configure the oh_dear_endpoint key

    In config/health.php, update the oh_dear_endpoint array with the following settings:

    • enabled: Set to true to activate the endpoint.
    • secret: A unique string used to protect the endpoint. It is recommended to store this in your .env file using the OH_DEAR_HEALTH_CHECK_SECRET key.
    • url: The path where the endpoint will be accessible (defaults to /oh-dear-health-check-results).
    • always_send_fresh_results: If true, health checks run immediately before responding. If false, the endpoint returns results from the last time checks were executed.

    3. Configure Oh Dear

    In your Oh Dear dashboard, navigate to the Application health settings for your site and enter the url and secret you configured in your Laravel app.

    // in app/config/health.php
    
    'oh_dear_endpoint' => [
        'enabled' => true,
    
        /*
         * When this option is enabled, the checks will run before sending a response.
         * Otherwise, we'll send the results from the last time the checks have run.
         */
        'always_send_fresh_results' => true,
    
        /*
         * The secret that is displayed at the Application Health settings at Oh Dear.
         */
        'secret' => env('OH_DEAR_HEALTH_CHECK_SECRET'),
    
        /*
         * The URL that should be configured in the Application health settings at Oh Dear.
         */
        'url' => '/oh-dear-health-check-results',
    ],
  6. Use the DatabaseCheck to verify DB connectivity

    main

    The DatabaseCheck ensures your application can successfully connect to a database. By default, it attempts to connect using your application's default database connection. If the default connection fails, the check will fail.

    To use this check, register it within the Health::checks() method.

    use Spatie\Health\Facades\Health;
    use Spatie\Health\Checks\Checks\DatabaseCheck;
    
    Health::checks([
        DatabaseCheck::new(),
    ]);
  7. Store health check results in the cache

    main

    You can use Spatie\Health\ResultStores\CacheHealthResultStore to write the latest health check results to your application's cache. This is useful for persisting check results across different requests or processes.

    To configure this, add the CacheHealthResultStore class to the result_stores array within the health configuration file. You must specify which cache driver to use via the store key. The value for store must match one of the cache stores defined in your config/cache.php file (e.g., file, redis, database).

    return [
        'result_stores' => [
            CacheHealthResultStore::class => [
                'store' => 'file', // Replace 'file' with your configured cache store name
            ],
        ],
    ];
  8. Use the HorizonCheck to monitor Laravel Horizon

    main

    The HorizonCheck ensures that Laravel Horizon is running. It reports a warning if Horizon is paused and a failure if Horizon is not running at all.

    To use it, register the check within your Health::checks() call.

    use Spatie\Health\Facades\Health;
    use Spatie\Health\Checks\Checks\HorizonCheck;
    
    Health::checks([
        HorizonCheck::new(),
    ]);
  9. Use HealthCheckJsonResultsController for detailed JSON health reports

    main

    The HealthCheckJsonResultsController returns a detailed JSON view of all executed health checks, including their individual statuses and metadata.

    Note: This endpoint always returns a 200 status code unless a critical error occurs. Because it exposes detailed internal information, it is highly recommended to protect this route with authentication middleware.

    Route::middleware('auth')->get('health', \Spatie\Health\Http\Controllers\HealthCheckJsonResultsController::class);