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

Nightwatch Laravel Package

laravel/nightwatch

Official Laravel Nightwatch package that collects application performance metrics and sends them to the hosted Nightwatch monitoring platform, providing Laravel-optimized insights into requests, errors, and overall app health.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require laravel/nightwatch
    
  2. Publish the config (optional, but recommended for customization):
    php artisan vendor:publish --provider="Laravel\Nightwatch\NightwatchServiceProvider" --tag="config"
    
  3. Set your API token in .env:
    NIGHTWATCH_API_TOKEN=your_api_token_here
    
  4. Verify installation by running:
    php artisan nightwatch:status
    

First Use Case: Monitoring HTTP Requests

Nightwatch automatically tracks HTTP requests, exceptions, and command execution. No additional code is needed for basic monitoring. To manually trigger a digest (forcing data transmission):

use Laravel\Nightwatch\Facades\Nightwatch;

Nightwatch::digest(); // Force immediate transmission of buffered data

Implementation Patterns

Core Workflows

  1. Automatic Instrumentation

    • HTTP requests, exceptions, and Artisan commands are tracked by default.
    • Example: Monitor a route with custom logic:
      use Laravel\Nightwatch\Facades\Nightwatch;
      
      Route::get('/custom-monitor', function () {
          Nightwatch::group('CustomGroup', ['key' => 'value']);
          // Your logic here
          Nightwatch::ungroup();
      });
      
  2. Sampling Control

    • Adjust sampling rates via .env:
      NIGHTWATCH_COMMAND_SAMPLE_RATE=0.1  # 10% of commands
      NIGHTWATCH_SCHEDULED_TASK_SAMPLE_RATE=0.5  # 50% of tasks
      
    • Override per-command:
      Nightwatch::sample(0.2); // 20% sample rate for this context
      
  3. Deploy Tracking

    • Use the nightwatch:deploy command to mark deployments:
      php artisan nightwatch:deploy --message="Hotfix for critical bug"
      
    • Automate in post-deploy hooks (e.g., Forge, Deployer):
      php artisan nightwatch:deploy --message="Production deploy"
      
  4. Exception Redaction

    • Redact sensitive data in exceptions:
      Nightwatch::redact('password', '****');
      

Integration Tips

  • Queue Jobs: Nightwatch captures job execution time and failures. Use Nightwatch::group() to nest job-specific metrics.
  • Scheduled Tasks: Sub-minute frequencies (e.g., vapor:schedule) are supported. Configure sampling separately:
    NIGHTWATCH_SCHEDULED_TASK_SAMPLE_RATE=0.3
    
  • Custom Metrics: Log custom events:
    Nightwatch::event('user_login', ['ip' => request()->ip()]);
    
  • Boost Skills: Use the configure-nightwatch Boost skill to auto-configure sampling and ignore rules.

Gotchas and Tips

Pitfalls

  1. Double Sampling

    • If NIGHTWATCH_COMMAND_SAMPLE_RATE and NIGHTWATCH_SCHEDULED_TASK_SAMPLE_RATE are both set, the latter takes precedence for scheduled tasks. Ensure alignment between them.
  2. Ignored Commands

    • Commands like schedule:finish and octane:status are ignored by default. To re-enable:
      Nightwatch::ignore(false);
      
  3. Payload Buffering

    • Data is batched and sent every 5 seconds or when the buffer exceeds 100 records. Force a digest with Nightwatch::digest() if needed (e.g., before a long-running process).
  4. Environment Variables

    • NIGHTWATCH_DEPLOY falls back to VAPOR_COMMIT_HASH if unset. Ensure consistency in CI/CD pipelines.
  5. Windows Compatibility

    • Streams (stdout/stderr) are written synchronously on Windows to avoid buffering issues.

Debugging

  • Check Status:

    php artisan nightwatch:status
    

    Outputs connection status, last digest time, and buffered events.

  • Log Levels: Enable debug logs in config/nightwatch.php:

    'log_level' => 'debug',
    
  • Manual Testing: Simulate events in tests:

    $this->artisan('nightwatch:test-event', ['event' => 'test_event']);
    

Extension Points

  1. Custom Event Handlers Extend the Nightwatch facade to add domain-specific events:

    Nightwatch::extend(function ($nightwatch) {
        $nightwatch->on('custom_event', function ($payload) {
            // Process payload
        });
    });
    
  2. Agent Configuration Override the agent URL or timeout in config/nightwatch.php:

    'agent' => [
        'url' => env('NIGHTWATCH_AGENT_URL', 'https://agent.nightwatch.laravel.com'),
        'timeout' => 5.0,
    ],
    
  3. Ignore Rules Dynamically ignore specific routes or commands:

    Nightwatch::ignore(function ($event) {
        return str_contains($event->getName(), 'admin.');
    });
    

Pro Tips

  • Sampling Strategies: Use higher sample rates (e.g., 0.5) for critical paths and lower rates (e.g., 0.1) for high-frequency, low-priority tasks.

  • Deploy Context: Attach deploy metadata (e.g., Git SHA, author) for traceability:

    php artisan nightwatch:deploy --message="Release v1.0" --sha="abc123"
    
  • Exception Context: Capture request payloads on unhandled exceptions for debugging:

    Nightwatch::captureRequestPayload(true);
    
  • Performance Impact: Nightwatch adds minimal overhead (~1-2ms per request). Monitor with nightwatch:status to verify.

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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony