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

Laravel Nightwatch package for Laravel apps: collects performance and application metrics and securely sends them to the hosted Nightwatch monitoring platform, providing deep Laravel-optimized insights into runtime behavior and overall health.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require laravel/nightwatch
    

    Publish the config file:

    php artisan vendor:publish --provider="Laravel\Nightwatch\NightwatchServiceProvider" --tag="config"
    
  2. Environment Configuration: Add your NIGHTWATCH_API_KEY and NIGHTWATCH_APP_ID to your .env:

    NIGHTWATCH_API_KEY=your_api_key
    NIGHTWATCH_APP_ID=your_app_id
    
  3. First Use Case: Run the nightwatch:deploy command to register your deployment:

    php artisan nightwatch:deploy
    

    This automatically sends metadata (PHP version, Laravel version, etc.) to Nightwatch.


Where to Look First

  • Configuration: config/nightwatch.php – Adjust sampling rates, ignored commands, and event filtering.
  • Facade: Use Nightwatch::ignore() or Nightwatch::digest() in your code for dynamic control.
  • Documentation: Official Nightwatch Docs for advanced features like custom events or Boost skills.

Implementation Patterns

Core Workflows

  1. Automatic Monitoring: The package passively monitors:

    • HTTP requests (response times, payloads, headers).
    • Database queries (connection, duration, SQL).
    • Queue jobs (processing time, exceptions).
    • Scheduled tasks (frequency, execution time).
    • Exceptions (stack traces, redacted data).

    No manual instrumentation needed for 90% of use cases.

  2. Sampling Control: Configure sampling rates in .env or config/nightwatch.php:

    NIGHTWATCH_COMMAND_SAMPLE_RATE=0.1  # 10% of commands
    NIGHTWATCH_SCHEDULED_TASK_SAMPLE_RATE=0.5  # 50% of tasks
    

    Override per-command or per-task:

    Nightwatch::ignore('command:foo'); // Exclude entirely
    Nightwatch::sample('command:bar', 0.3); // Custom rate
    
  3. Custom Events: Emit arbitrary events for business logic:

    Nightwatch::event('user.purchased', [
        'user_id' => auth()->id(),
        'amount' => $order->total,
    ]);
    
  4. Deployment Tracking: Use the nightwatch:deploy command before releases:

    php artisan nightwatch:deploy --message="Hotfix for payment bug"
    

    Or programmatically:

    Nightwatch::deploy('feature/x', 'Deployed new checkout flow');
    

Integration Tips

  • Octane Support: Nightwatch automatically adapts to Octane’s async workers. Exclude Octane-specific commands (e.g., octane:status) via config:

    'ignored_commands' => [
        'octane:*',
    ],
    
  • Queue Workers: Run queue:listen with --timeout=0 to avoid artificial timeouts skewing metrics.

  • Testing: Use the Nightwatch::fake() helper in tests to mock events:

    Nightwatch::fake();
    $this->assertNightwatchEvents(function () {
        // Test code triggering events
    });
    
  • Boost Skills: Leverage pre-built skills (e.g., configure-nightwatch) via Laravel Boost:

    composer require laravel/boost
    php artisan boost:skill configure-nightwatch
    

Gotchas and Tips

Pitfalls

  1. Sampling Conflicts:

    • NIGHTWATCH_SCHEDULED_TASK_SAMPLE_RATE now takes precedence over NIGHTWATCH_COMMAND_SAMPLE_RATE for scheduled tasks (v1.20+).
    • Fix: Update both rates if you rely on shared sampling.
  2. Ignored Commands:

    • The package ignores schedule:finish by default (v1.19+). If you need to monitor it, remove it from ignored_commands.
  3. Octane Quirks:

    • First request latency includes bootstrapping time. Use Nightwatch::digest() to manually flush metrics if needed.
  4. Redaction:

    • Exception data is redacted by default (v1.18+). Customize via:
      Nightwatch::redact(function ($data) {
          $data['password'] = '[redacted]';
          return $data;
      });
      
  5. Windows Streams:

    • Output to stderr/stdout is synchronous on Windows (v1.17.1). For async logging, use a separate channel.

Debugging

  • Payload Inspection: Enable debug mode in config/nightwatch.php:

    'debug' => env('NIGHTWATCH_DEBUG', false),
    

    Logs payloads to storage/logs/nightwatch.log.

  • Network Issues: Check the agent’s HTTP requests with:

    tail -f storage/logs/nightwatch.log | grep "POST /api/ingest"
    

    Common fixes:

    • Ensure NIGHTWATCH_API_KEY and NIGHTWATCH_APP_ID are correct.
    • Verify the agent can reach https://api.nightwatch.laravel.com.
  • Flaky Tests: Use Nightwatch::fake() to isolate tests. For flaky queue:listen tests, set a fixed timeout:

    $this->artisan('queue:listen', ['--timeout' => 1])->assertExitCode(0);
    

Extension Points

  1. Custom Event Filters: Register callbacks to filter events before ingestion:

    Nightwatch::filter(function ($event) {
        return !str_contains($event['name'], 'internal.');
    });
    
  2. Agent Core Access: Access the underlying Core class for advanced use:

    $core = app(\Laravel\Nightwatch\Core::class);
    $core->setOption('buffer_limit', 100); // Custom buffer size
    
  3. Deployment Metadata: Extend deployment data via environment variables:

    NIGHTWATCH_DEPLOY_BRANCH=main
    NIGHTWATCH_DEPLOY_COMMIT=abc123
    

    Fallbacks: VAPOR_COMMIT_HASH, GITHUB_SHA, etc.

  4. Boost Skills: Create custom skills to automate Nightwatch setup:

    php artisan make:boost-skill my-nightwatch-config
    

Pro Tips

  • Proactive Digestion: Use Nightwatch::digest() to force-sync events during critical paths (e.g., payment processing):

    try {
        $payment->charge();
        Nightwatch::digest(); // Ensure metrics are sent
    } catch (\Exception $e) {
        Nightwatch::event('payment.failed', ['error' => $e->getMessage()]);
    }
    
  • Sampling by Context: Dynamically adjust sampling based on user roles:

    if (auth()->user()->isPremium()) {
        Nightwatch::sample('command:expensive', 1.0); // 100% sampling for premium users
    }
    
  • Local Testing: Use the NIGHTWATCH_API_URL env var to point to a local Nightwatch instance for testing:

    NIGHTWATCH_API_URL=http://nightwatch.test/api
    
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