stackwatch / laravel
StackWatch Laravel SDK - AI-powered application monitoring for Laravel
Requires
- php: ^8.1
- guzzlehttp/guzzle: ^7.0
- illuminate/cache: ^10.0|^11.0|^12.0
- illuminate/http: ^10.0|^11.0|^12.0
- illuminate/support: ^10.0|^11.0|^12.0
Requires (Dev)
- orchestra/testbench: ^8.0|^9.0
- phpunit/phpunit: ^10.0|^11.0
Suggests
- spatie/laravel-activitylog: Required for activity log monitoring (^4.0)
- spatie/laravel-backup: Required for backup event monitoring (^8.0)
- spatie/laravel-health: Required for health check monitoring (^1.0)
README
AI-powered application monitoring for Laravel applications.
Features
- ๐ด Error Tracking - Automatic exception capture with full stack traces
- ๐ค AI Analysis - Get AI-powered insights and fix suggestions
- โก Performance Monitoring - Track response times and slow queries
- ๐ Breadcrumbs - Automatic logging of events leading up to errors
- ๐ค User Context - Automatically capture authenticated user info
- ๐ Log Integration - Capture all Laravel logs (debug, info, warning, error)
- ๐พ Backup Monitoring - Spatie Laravel Backup integration
- ๐ฅ Health Checks - Spatie Laravel Health integration
- ๐ Activity Logging - Spatie Activity Log integration
- ๐ Notifications - Get alerted via Slack, Discord, or email
- โฑ๏ธ Rate Limiting - Smart rate limiting with event buffering
Requirements
- PHP 8.1+
- Laravel 10.x, 11.x, or 12.x
Installation
Quick Install (Recommended)
composer require stackwatch/laravel php artisan stackwatch:install
The install command will guide you through:
- Publishing the configuration
- Setting up your API key
- Testing the connection
Manual Install
composer require stackwatch/laravel php artisan vendor:publish --tag=stackwatch-config
Add to .env:
STACKWATCH_API_KEY=your-api-key-here STACKWATCH_ENVIRONMENT=production
Test your installation:
php artisan stackwatch:test
Usage
Automatic Exception Capture
Exceptions are automatically captured and sent to StackWatch. No additional code needed!
Manual Exception Reporting
use StackWatch\Laravel\Facades\StackWatch; try { // Your code } catch (Exception $e) { StackWatch::captureException($e); }
Capture Messages
use StackWatch\Laravel\Facades\StackWatch; // Info message StackWatch::captureMessage('User signed up', 'info', [ 'plan' => 'pro', ]); // Warning StackWatch::captureMessage('Rate limit approaching', 'warning'); // Error StackWatch::captureMessage('Payment failed', 'error', [ 'user_id' => $user->id, ]);
Capture Custom Events
use StackWatch\Laravel\Facades\StackWatch; // Backup event StackWatch::captureEvent('backup', 'info', 'Daily backup completed', [ 'size' => '2.5 GB', 'duration' => '5 minutes', ]); // Health check StackWatch::captureEvent('health', 'warning', 'Disk space low', [ 'disk' => 'primary', 'usage' => '85%', ]);
Add Custom Context
use StackWatch\Laravel\Facades\StackWatch; // Set user context StackWatch::setUser([ 'id' => $user->id, 'email' => $user->email, 'name' => $user->name, ]); // Add tags StackWatch::setTag('feature', 'checkout'); StackWatch::setTags([ 'version' => '2.0', 'region' => 'eu-west', ]); // Add extra context StackWatch::setExtra('order_id', $order->id); // Add custom context StackWatch::setContext('payment', [ 'provider' => 'stripe', 'amount' => 9900, ]);
Add Breadcrumbs
use StackWatch\Laravel\Facades\StackWatch; StackWatch::addBreadcrumb('user', 'Clicked checkout button'); StackWatch::addBreadcrumb('api', 'Called payment API', [ 'provider' => 'stripe', 'amount' => 9900, ]);
Log Integration
StackWatch can capture all Laravel logs as separate events.
Option 1: Auto-register (Recommended)
Add to .env:
STACKWATCH_AUTO_REGISTER_LOG=true STACKWATCH_LOG_LEVEL=debug STACKWATCH_CAPTURE_LOGS_AS_EVENTS=true
Option 2: Manual Configuration
In config/logging.php:
'channels' => [ 'stack' => [ 'driver' => 'stack', 'channels' => ['daily', 'stackwatch'], ], 'stackwatch' => [ 'driver' => 'custom', 'via' => \StackWatch\Laravel\Logging\StackWatchLogChannel::class, 'level' => env('STACKWATCH_LOG_LEVEL', 'debug'), ], ],
Log Sampling
To reduce volume for high-traffic applications:
# Only send 10% of info/debug logs (errors always sent) STACKWATCH_LOG_SAMPLE_RATE=0.1
Middleware
Add the middleware to capture request context and performance data:
// app/Http/Kernel.php (Laravel 10) protected $middleware = [ // ... \StackWatch\Laravel\Middleware\StackWatchMiddleware::class, ]; // Or for specific routes Route::middleware(['stackwatch'])->group(function () { // Routes }); // Laravel 11+ (bootstrap/app.php) ->withMiddleware(function (Middleware $middleware) { $middleware->append(\StackWatch\Laravel\Middleware\StackWatchMiddleware::class); })
Integrations
Spatie Laravel Backup
Automatically monitors your backups when spatie/laravel-backup is installed.
composer require spatie/laravel-backup
Events captured:
- โ Backup successful
- โ Backup failed
- ๐งน Cleanup successful/failed
- ๐ฅ Backup health checks
To disable:
STACKWATCH_SPATIE_BACKUP_ENABLED=false
Spatie Laravel Health
Monitors health checks when spatie/laravel-health is installed.
composer require spatie/laravel-health
Only failed or warning health checks are sent to reduce noise.
To disable:
STACKWATCH_SPATIE_HEALTH_ENABLED=false
Spatie Activity Log
Captures activity logs when spatie/laravel-activitylog is installed.
composer require spatie/laravel-activitylog
Filter by log name or event type in config/stackwatch.php:
'integrations' => [ 'spatie_activitylog' => [ 'enabled' => true, 'log_names' => ['default', 'audit'], // Only these log names 'event_types' => ['created', 'deleted'], // Only these events ], ],
Rate Limiting
StackWatch includes smart rate limiting to prevent overwhelming the API:
# Maximum events per minute STACKWATCH_RATE_LIMIT_PER_MINUTE=60
When rate limited, events are automatically buffered and sent with the next successful request. No events are lost!
To disable buffering (drop events when rate limited):
// config/stackwatch.php 'rate_limit' => [ 'buffer_on_limit' => false, ],
Performance Monitoring
Performance monitoring is enabled by default with smart defaults to minimize overhead:
Transaction Grouping
Configure how requests are grouped for aggregation:
# Group by full path (default) - each unique URL tracked separately # e.g., "GET /blog/post-1", "GET /blog/post-2" STACKWATCH_PERFORMANCE_GROUP_BY=path # Group by route name - same endpoint grouped together # e.g., "GET blog.show" (includes all blog posts) STACKWATCH_PERFORMANCE_GROUP_BY=route
Aggregation (Default)
Instead of sending every request, StackWatch aggregates metrics and sends summaries:
- Collects requests until batch size reached (default: 50)
- Sends aggregated stats: avg/min/max duration, error rate, request count
- Time-based flush: after interval passes AND minimum count reached
- Prevents sending useless aggregates with only 1-2 requests
# Disable aggregation (send individual requests with sampling) STACKWATCH_PERFORMANCE_AGGREGATE=false # Number of requests to trigger immediate aggregate send STACKWATCH_PERFORMANCE_BATCH_SIZE=50 # Seconds to wait before time-based flush STACKWATCH_PERFORMANCE_FLUSH_INTERVAL=60 # Minimum requests required for time-based flush # If only 3 requests after 60s, wait until 5 or batch_size reached STACKWATCH_PERFORMANCE_MIN_FLUSH_COUNT=5
Slow Requests
Requests slower than the threshold are always sent immediately (not aggregated):
# Requests over 3000ms (3s) are always reported (default) STACKWATCH_SLOW_REQUEST_THRESHOLD=3000 # Lower threshold for more sensitive monitoring STACKWATCH_SLOW_REQUEST_THRESHOLD=1000
Sampling (When Aggregation Disabled)
If aggregation is disabled, sampling controls how many requests are sent:
# Only send 10% of requests (default) STACKWATCH_PERFORMANCE_SAMPLE_RATE=0.1 # Send all requests (not recommended for production) STACKWATCH_PERFORMANCE_SAMPLE_RATE=1.0
Disable Performance Monitoring
STACKWATCH_PERFORMANCE_ENABLED=false
Deployment Notifications
Notify StackWatch when you deploy:
php artisan stackwatch:deploy --release=v1.2.3
Or in your CI/CD pipeline:
php artisan stackwatch:deploy --release=$GITHUB_SHA
Environment Variables
| Variable | Description | Default |
|---|---|---|
STACKWATCH_API_KEY |
Your API key (required) | - |
STACKWATCH_ENDPOINT |
API endpoint | https://api.stackwatch.dev/v1 |
STACKWATCH_ENVIRONMENT |
Environment name | APP_ENV |
STACKWATCH_RELEASE |
Release version | APP_VERSION |
STACKWATCH_ENABLED |
Enable/disable | true |
STACKWATCH_CAPTURE_EXCEPTIONS |
Auto-capture exceptions | true |
STACKWATCH_LOG_LEVEL |
Minimum log level | debug |
STACKWATCH_CAPTURE_LOGS_AS_EVENTS |
Send logs as events | true |
STACKWATCH_AUTO_REGISTER_LOG |
Auto-add to log stack | false |
STACKWATCH_LOG_SAMPLE_RATE |
Log sampling rate (0-1) | 1.0 |
STACKWATCH_RATE_LIMIT_PER_MINUTE |
Rate limit | 60 |
STACKWATCH_PERFORMANCE_ENABLED |
Performance monitoring | true |
STACKWATCH_PERFORMANCE_GROUP_BY |
Group by 'path' or 'route' | path |
STACKWATCH_PERFORMANCE_SAMPLE_RATE |
Performance sampling (when aggregation disabled) | 0.1 |
STACKWATCH_PERFORMANCE_AGGREGATE |
Aggregate performance metrics | true |
STACKWATCH_PERFORMANCE_BATCH_SIZE |
Requests before sending aggregate | 50 |
STACKWATCH_PERFORMANCE_FLUSH_INTERVAL |
Seconds before time-based flush | 60 |
STACKWATCH_PERFORMANCE_MIN_FLUSH_COUNT |
Min requests for time-based flush | 5 |
STACKWATCH_SLOW_REQUEST_THRESHOLD |
Slow request threshold (ms) | 3000 |
STACKWATCH_SPATIE_BACKUP_ENABLED |
Backup integration | true |
STACKWATCH_SPATIE_HEALTH_ENABLED |
Health integration | true |
STACKWATCH_SPATIE_ACTIVITYLOG_ENABLED |
Activity log integration | true |
Troubleshooting
Events not appearing
-
Check your API key:
php artisan stackwatch:test
-
Check for rate limiting:
# View buffered events count php artisan tinker >>> app(\StackWatch\Laravel\Transport\HttpTransport::class)->getBufferSize()
High memory usage
Reduce breadcrumb count:
// config/stackwatch.php 'breadcrumbs' => [ 'max_breadcrumbs' => 20, // Default: 50 ],
Too many events
Use sampling:
STACKWATCH_LOG_SAMPLE_RATE=0.1 STACKWATCH_PERFORMANCE_SAMPLE_RATE=0.5
Testing
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security
If you discover any security-related issues, please email security@stackwatch.dev instead of using the issue tracker.
License
The MIT License (MIT). Please see License File for more information. 'max_breadcrumbs' => 50, 'capture_logs' => true, 'capture_queries' => true, ],
// Performance monitoring
'performance' => [
'enabled' => true,
'sample_rate' => 1.0, // 0.0 to 1.0
'slow_query_threshold' => 100, // ms
],
// Ignored exceptions
'ignored_exceptions' => [
\Illuminate\Auth\AuthenticationException::class,
\Symfony\Component\HttpKernel\Exception\NotFoundHttpException::class,
],
];
## Testing
```bash
composer test
License
MIT License. See LICENSE for details.