# Recording Modes ChronoTrace offers flexible recording modes to suit different environments and use cases. Choose the right mode to balance debugging capabilities with performance and storage requirements. --- ## 🎛️ Overview Recording modes determine **when** ChronoTrace captures traces: | Mode | Best For | Captures | Performance Impact | Storage Usage | |------|----------|----------|-------------------|---------------| | `always` | Development | Every request | High | Very High | | `sample` | Staging/Testing | Random percentage | Medium | Medium | | `record_on_error` | Production | Errors + samples | Low | Low | | `targeted` | Debugging | Specific routes/conditions | Very Low | Very Low | --- ## 🔧 Configuration Set the recording mode in your `.env` file: ```bash CHRONOTRACE_MODE=record_on_error CHRONOTRACE_SAMPLE_RATE=0.001 ``` Or in the configuration file: ```php // config/chronotrace.php 'mode' => env('CHRONOTRACE_MODE', 'record_on_error'), 'sample_rate' => env('CHRONOTRACE_SAMPLE_RATE', 0.001), ``` --- ## 📊 Always Mode **Perfect for development environments where you want complete visibility.** ### Configuration ```bash CHRONOTRACE_MODE=always CHRONOTRACE_ENABLED=true ``` ### Behavior - ✅ Records **every single request** - ✅ Captures all events (DB, cache, HTTP, jobs) - ✅ No sampling or filtering - ✅ Immediate trace availability ### Use Cases ```bash # Development debugging - Understanding application flow - Learning how features work - Comprehensive testing - Performance profiling # Team collaboration - Sharing exact request traces - Documenting complex workflows - Code review assistance ``` ### Example Output ```bash $ php artisan chronotrace:list ┌────────────┬─────────────────────┬────────┬──────────┬─────────────────┬──────────┐ │ Trace ID │ Timestamp │ Method │ Status │ Route │ Duration │ ├────────────┼─────────────────────┼────────┼──────────┼─────────────────┼──────────┤ │ req_001 │ 2024-08-06 14:30:15 │ GET │ 200 │ / │ 45ms │ │ req_002 │ 2024-08-06 14:30:16 │ GET │ 200 │ /api/users │ 89ms │ │ req_003 │ 2024-08-06 14:30:17 │ POST │ 201 │ /api/users │ 156ms │ │ req_004 │ 2024-08-06 14:30:18 │ GET │ 200 │ /dashboard │ 234ms │ └────────────┴─────────────────────┴────────┴──────────┴─────────────────┴──────────┘ ``` ### Considerations ⚠️ **High storage usage** - Clean up regularly ⚠️ **Performance impact** - Use only in development ⚠️ **Sensitive data** - Ensure PII scrubbing is enabled --- ## 🎲 Sample Mode **Ideal for staging environments and performance monitoring.** ### Configuration ```bash CHRONOTRACE_MODE=sample CHRONOTRACE_SAMPLE_RATE=0.1 # 10% of requests ``` ### Advanced Sampling ```php // config/chronotrace.php 'sampling' => [ 'base_rate' => 0.05, // 5% base sampling 'error_rate' => 1.0, // Always capture errors 'slow_request_threshold' => 1000, // Requests > 1s 'slow_request_rate' => 0.5, // 50% of slow requests 'user_based_sampling' => [ 'admin_users' => 0.2, // 20% for admins 'beta_users' => 0.15, // 15% for beta testers 'regular_users' => 0.02, // 2% for regular users ], ], ``` ### Behavior - ✅ Records random percentage of requests - ✅ **Always captures errors** regardless of sample rate - ✅ Can prioritize slow requests - ✅ Configurable per user type ### Use Cases ```bash # Staging environment - Load testing analysis - Performance trend monitoring - Feature rollout monitoring - Integration testing # Pre-production validation - Representative traffic sampling - Performance baseline establishment - Error rate monitoring ``` ### Sample Rate Guidelines | Environment | Sample Rate | Rationale | |-------------|-------------|-----------| | Local Development | 1.0 (100%) | Full visibility needed | | Staging | 0.1 (10%) | Representative sampling | | Load Testing | 0.05 (5%) | Reduce overhead during tests | | Pre-production | 0.02 (2%) | Light monitoring | ### Example Configuration by Traffic Volume ```php // High traffic (>10k requests/day) 'sample_rate' => 0.001, // 0.1% // Medium traffic (1k-10k requests/day) 'sample_rate' => 0.01, // 1% // Low traffic (<1k requests/day) 'sample_rate' => 0.1, // 10% ``` --- ## 🚨 Record on Error Mode **Recommended for production environments.** ### Configuration ```bash CHRONOTRACE_MODE=record_on_error CHRONOTRACE_SAMPLE_RATE=0.001 # 0.1% of successful requests ``` ### Behavior - ✅ **Always records errors** (4xx, 5xx status codes) - ✅ Records small sample of successful requests - ✅ Minimal performance impact - ✅ Storage-efficient ### Error Detection ```php // Automatically captures these scenarios: - HTTP 400-499 (Client errors) - HTTP 500-599 (Server errors) - PHP exceptions - Database query failures - External API failures - Queue job failures ``` ### Custom Error Conditions ```php // config/chronotrace.php 'error_conditions' => [ 'status_codes' => [400, 401, 403, 404, 422, 500, 502, 503], 'slow_requests' => 5000, // > 5 seconds 'memory_threshold' => 128 * 1024 * 1024, // > 128MB 'custom_conditions' => [ 'failed_payment' => function ($request, $response) { return $request->is('api/payments/*') && $response->status() >= 400; }, ], ], ``` ### Use Cases ```bash # Production monitoring - Error tracking and debugging - Performance issue detection - API failure monitoring - Payment processing errors # Incident response - Post-mortem analysis - Root cause investigation - Error reproduction - Timeline reconstruction ``` ### Example Production Configuration ```php return [ 'mode' => 'record_on_error', 'sample_rate' => 0.0005, // 0.05% of successful requests 'capture' => [ 'database' => true, 'http' => true, 'jobs' => true, 'cache' => false, // Reduce noise 'events' => false, // Reduce noise ], 'retention_days' => 7, // Short retention 'async_storage' => true, // Performance ]; ``` --- ## 🎯 Targeted Mode **Perfect for debugging specific features or routes.** ### Configuration ```bash CHRONOTRACE_MODE=targeted ``` ### Route Targeting ```php // config/chronotrace.php 'targeted_routes' => [ 'api/orders/*', 'api/payments/*', 'checkout/*', 'admin/users/*', ], ``` ### Condition-Based Targeting ```php // config/chronotrace.php 'targeted_conditions' => [ // Specific users 'user_ids' => [123, 456, 789], // IP addresses 'ip_addresses' => ['192.168.1.100', '10.0.0.50'], // User agents 'user_agents' => ['TestRunner/*', 'Postman/*'], // Custom headers 'headers' => [ 'X-Debug-Session' => 'active', 'X-Feature-Flag' => 'new-checkout', ], // Query parameters 'query_params' => [ 'debug' => 'true', 'trace' => 'enabled', ], ], ``` ### Dynamic Targeting ```php // Enable targeting for specific sessions Route::middleware(['chronotrace.targeted'])->group(function () { Route::post('/api/orders', [OrderController::class, 'store']); Route::get('/api/orders/{order}', [OrderController::class, 'show']); }); ``` ### Use Cases ```bash # Feature debugging - New feature development - Bug reproduction - Performance optimization - Integration testing # User-specific issues - Customer support debugging - VIP user monitoring - Beta feature testing - A/B testing analysis ``` ### Targeted Session Management ```bash # Start targeted recording for specific user php artisan chronotrace:target --user-id=123 --duration=1h # Target specific routes temporarily php artisan chronotrace:target --routes="api/orders/*" --duration=30m # Target by IP address php artisan chronotrace:target --ip="192.168.1.100" --duration=15m ``` --- ## 🔄 Dynamic Mode Switching ### Runtime Mode Changes ```bash # Temporarily enable full recording php artisan chronotrace:record --mode=always --duration=5m # Switch to error-only mode php artisan chronotrace:mode record_on_error # Enable targeted recording php artisan chronotrace:mode targeted --routes="api/payments/*" ``` ### Programmatic Control ```php // In your application code use Grazulex\LaravelChronotrace\Facades\ChronoTrace; // Temporarily change mode ChronoTrace::setMode('always')->for(minutes: 5); // Enable for specific request ChronoTrace::enableForCurrentRequest(); // Force recording regardless of mode ChronoTrace::forceRecord(); ``` ### Environment-Based Switching ```php // config/chronotrace.php 'mode' => match(app()->environment()) { 'local' => 'always', 'testing' => 'sample', 'staging' => 'sample', 'production' => 'record_on_error', default => 'record_on_error', }, ``` --- ## 📈 Performance Comparison ### Request Overhead by Mode | Mode | CPU Overhead | Memory Overhead | Storage/Day | |------|--------------|-----------------|-------------| | `always` | ~5-15ms | ~2-5MB | ~500MB-2GB | | `sample` (10%) | ~0.5-1.5ms | ~0.2-0.5MB | ~50-200MB | | `record_on_error` | ~0.1-0.5ms | ~0.1-0.2MB | ~5-50MB | | `targeted` | ~0.05-0.2ms | ~0.05-0.1MB | ~1-10MB | *Note: Actual overhead depends on application complexity and event types captured.* ### Optimization Tips ```php // Reduce overhead in any mode 'capture' => [ 'database' => true, // Essential 'http' => true, // Important for APIs 'jobs' => true, // Important for async work 'cache' => false, // Often noisy 'events' => false, // Very verbose ], // Use async storage 'async_storage' => true, 'queue_connection' => 'redis', // Limit trace size 'memory' => [ 'max_trace_size' => 5 * 1024 * 1024, // 5MB limit ], ``` --- ## 🛠️ Mode Selection Guide ### Choose `always` when: - ✅ Developing new features - ✅ Learning application behavior - ✅ Debugging complex issues - ✅ Creating documentation - ❌ **Never in production** ### Choose `sample` when: - ✅ Staging environment testing - ✅ Performance monitoring - ✅ Load testing analysis - ✅ Feature rollout monitoring ### Choose `record_on_error` when: - ✅ Production monitoring - ✅ Error tracking - ✅ Incident response - ✅ Minimal overhead required ### Choose `targeted` when: - ✅ Debugging specific features - ✅ Customer support issues - ✅ Performance optimization - ✅ Beta testing --- ## 📊 Monitoring Mode Effectiveness ### Metrics to Track ```bash # Trace volume and coverage php artisan chronotrace:stats --mode-effectiveness # Storage usage by mode php artisan chronotrace:diagnose --storage --mode-breakdown # Performance impact analysis php artisan chronotrace:performance --compare-modes ``` ### Example Monitoring Dashboard ```bash # Daily metrics - Total requests: 10,000 - Traces captured: 50 (0.5%) - Errors captured: 15/15 (100%) - Storage used: 25MB - Average overhead: 0.2ms ``` --- ## 🔧 Advanced Configuration ### Multi-Environment Mode ```php // config/chronotrace.php 'multi_mode' => [ 'api_routes' => 'record_on_error', 'admin_routes' => 'sample', 'payment_routes' => 'always', // Critical flows 'public_routes' => 'targeted', ], ``` ### Conditional Mode Logic ```php 'mode_resolver' => function ($request) { if ($request->header('X-Debug-Mode')) { return 'always'; } if ($request->is('api/payments/*')) { return 'record_on_error'; } return 'sample'; }, ``` --- ## 📚 Related Documentation - **[Configuration](Configuration.md)** - Complete configuration options - **[Commands](Commands.md)** - Mode control commands - **[Production Monitoring](Production-Monitoring.md)** - Production mode best practices --- **Need help choosing the right mode?** Check our [Configuration Examples](Configuration-Examples.md) for ready-to-use configurations for common scenarios.