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

Health Check Bundle Laravel Package

duc01nguyen/health-check-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Run:

    composer require duc01nguyen/health-check-bundle
    

    (Note: The README mentions niklesh/health-check-bundle, but the package name in the prompt is duc01nguyen/health-check-bundle. Use the correct one.)

  2. Publish Config Publish the required configuration files:

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

    This generates:

    • config/routes/health_check.yaml (required)
    • config/health_check.php (optional, if the package supports it)
  3. Configure Routes Edit config/routes/health_check.yaml:

    health_check:
      path: /health
      controller: App\Http\Controllers\HealthController
      methods: [GET]
    

    (Note: The README uses @HealthCheckBundle/Controller/HealthController.php, but Laravel typically expects a class path or FQCN. Verify the package’s actual route configuration format.)

  4. Run Migrations (if applicable) Check if the package includes migrations (e.g., for storing health check results):

    php artisan migrate
    
  5. Test the Endpoint Visit /health in your browser or via curl:

    curl http://your-app.test/health
    

    Expected output: A JSON response indicating system health (e.g., {"status": "healthy", "checks": {...}}).


First Use Case: Basic Health Endpoint

Use the /health endpoint to:

  • Monitor application uptime (e.g., via external tools like Prometheus, Datadog, or custom scripts).
  • Quickly diagnose issues during deployments or incidents.
  • Example response:
    {
      "status": "healthy",
      "checks": {
        "database": true,
        "cache": true,
        "queue": false,
        "message": "Queue worker not running"
      }
    }
    

Implementation Patterns

Core Workflows

  1. Customizing Health Checks Extend the bundle by adding custom checks. For example, create a service to verify a third-party API:

    // app/Services/CustomHealthCheck.php
    namespace App\Services;
    
    use Duc01nguyen\HealthCheckBundle\Contracts\HealthCheckInterface;
    
    class CustomHealthCheck implements HealthCheckInterface
    {
        public function check(): array
        {
            $response = http_get('https://api.example.com/status');
            return [
                'status' => $response['status'] === 200,
                'message' => $response['status'] === 200 ? 'API is healthy' : 'API failed',
            ];
        }
    }
    

    Register it in config/health_check.php (if supported):

    'checks' => [
        \App\Services\CustomHealthCheck::class,
    ],
    
  2. Integrating with Monitoring Tools Use the /health endpoint in your monitoring stack:

    • Prometheus: Scrape the endpoint and expose metrics. Example Prometheus rule:
      scrape_configs:
        - job_name: 'laravel_health'
          metrics_path: '/health'
          static_configs:
            - targets: ['your-app.test']
      
    • Uptime Robot: Ping the endpoint and alert on failures.
  3. Sending Health Info via CLI The health:send-info command (mentioned in the README) can be used to:

    • Log health status to a remote service (e.g., Slack, Datadog).
    • Trigger alerts programmatically. Example usage:
    php artisan health:send-info
    
  4. Conditional Checks Dynamically enable/disable checks based on environment:

    // In a custom check service
    public function check(): array
    {
        if (app()->environment('production')) {
            return $this->runProductionChecks();
        }
        return ['status' => true, 'message' => 'Development mode - skipping checks'];
    }
    

Integration Tips

  • Middleware: Protect the /health endpoint with middleware (e.g., auth:api) if it contains sensitive data.
  • Caching: Cache the health response for a few seconds to reduce load:
    Route::get('/health', function () {
        return Cache::remember('health_check', now()->addSeconds(5), function () {
            return HealthChecker::checkAll();
        });
    });
    
  • Rate Limiting: Limit requests to /health to prevent abuse:
    Route::middleware(['throttle:60,1'])->group(function () {
        // Health routes
    });
    
  • Local Development: Mock health checks in phpunit.xml:
    <env name="HEALTH_CHECK_MOCK" value="true"/>
    

Gotchas and Tips

Pitfalls

  1. Route Configuration Mismatch

    • The README suggests using @HealthCheckBundle/Controller/HealthController.php, but Laravel typically expects a class path (e.g., Duc01nguyen\HealthCheckBundle\Controller\HealthController).
    • Fix: Check the package’s actual route configuration format or source code. If unsure, inspect the routes/health_check.yaml file after publishing.
  2. Missing Dependencies

    • The package may require additional services (e.g., database, cache) to function. Ensure these are configured in .env.
    • Fix: Add health checks for these dependencies explicitly:
      // app/Services/DatabaseHealthCheck.php
      public function check(): array {
          try {
              DB::connection()->getPdo();
              return ['status' => true];
          } catch (\Exception $e) {
              return ['status' => false, 'message' => $e->getMessage()];
          }
      }
      
  3. Command Not Found

    • The health:send-info command may not exist or may require configuration.
    • Fix: Verify the command is registered in app/Console/Kernel.php:
      protected $commands = [
          // ...
          \Duc01nguyen\HealthCheckBundle\Console\SendHealthInfo::class,
      ];
      
  4. Performance Overhead

    • Running multiple checks in /health can slow down responses.
    • Fix: Use Laravel’s parallel helper or queue checks:
      use Illuminate\Support\Facades\Bus;
      
      $results = Bus::parallel([
          new CustomHealthCheck(),
          new DatabaseHealthCheck(),
      ])->then(function ($results) {
          return collect($results)->pluck('check');
      });
      
  5. Configuration File Confusion

    • The README mentions hiklesh_health.yaml, but the package name is duc01nguyen/health-check-bundle.
    • Fix: Use config/health_check.php (if the package supports it) or check the package’s documentation for the correct config path.

Debugging Tips

  1. Log Health Check Results Add logging to debug failing checks:

    public function check(): array {
        $result = ['status' => false];
        try {
            // Your check logic
            $result['status'] = true;
        } catch (\Exception $e) {
            \Log::error('Health check failed: ' . $e->getMessage());
            $result['message'] = $e->getMessage();
        }
        return $result;
    }
    
  2. Test Locally Simulate failures to test your health checks:

    // In a test
    $this->app->instance(
        \Duc01nguyen\HealthCheckBundle\Contracts\DatabaseChecker::class,
        new class implements \Duc01nguyen\HealthCheckBundle\Contracts\DatabaseChecker {
            public function isHealthy(): bool { return false; }
        }
    );
    
  3. Check Package Events Listen for health check events (if the package emits them):

    // In a service provider
    event(new \Duc01nguyen\HealthCheckBundle\Events\HealthCheckFailed($checkName, $message));
    

Extension Points

  1. Custom Response Format Override the default JSON response by binding a custom formatter:

    // app/Providers/AppServiceProvider.php
    public function boot() {
        $this->app->bind(
            \Duc01nguyen\HealthCheckBundle\Contracts\HealthResponseFormatter::class,
            \App\Services\CustomHealthResponseFormatter::class
        );
    }
    
  2. Add Check Metadata Extend checks to include metadata (e.g., severity, tags):

    public function check(): array {
        return [
            'status' => true,
            'message' => 'Database is healthy',
            'metadata' => [
                'severity' => 'low',
                'tags' => ['database', 'critical'],
            ],
        ];
    }
    
  3. Webhook Integration Send health check results to a webhook:

    // In a custom sender service
    public
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware