Skip to content

Event Capturing

Jean-Marc Strauven edited this page Aug 6, 2025 · 2 revisions

Event Capturing

Configure what events ChronoTrace captures during request execution to balance debugging capabilities with performance and storage requirements.


🎯 Overview

ChronoTrace can capture various types of events during Laravel request execution. You can selectively enable/disable event types based on your debugging needs and performance requirements.

Available Event Types

Event Type Purpose Performance Impact Storage Impact Default
Database SQL queries and transactions Low Medium βœ… Enabled
Cache Cache operations (get, set, forget) Very Low Low βœ… Enabled
HTTP External API calls Low High βœ… Enabled
Jobs Queue job dispatching Very Low Low βœ… Enabled
Events Laravel events Medium High ❌ Disabled
Logs Application logs High Very High ❌ Disabled

βš™οΈ Basic Configuration

Environment Variables

# .env - Basic event capture settings
CHRONOTRACE_CAPTURE_DATABASE=true
CHRONOTRACE_CAPTURE_CACHE=true
CHRONOTRACE_CAPTURE_HTTP=true
CHRONOTRACE_CAPTURE_JOBS=true
CHRONOTRACE_CAPTURE_EVENTS=false
CHRONOTRACE_CAPTURE_LOGS=false

Configuration File

// config/chronotrace.php
'capture' => [
    'database' => env('CHRONOTRACE_CAPTURE_DATABASE', true),
    'cache' => env('CHRONOTRACE_CAPTURE_CACHE', true),
    'http' => env('CHRONOTRACE_CAPTURE_HTTP', true),
    'jobs' => env('CHRONOTRACE_CAPTURE_JOBS', true),
    'events' => env('CHRONOTRACE_CAPTURE_EVENTS', false),
    'logs' => env('CHRONOTRACE_CAPTURE_LOGS', false),
],

πŸ—ƒοΈ Database Event Capturing

What's Captured

Database events include:

  • SQL queries with bindings and execution time
  • Transaction boundaries (begin, commit, rollback)
  • Connection information and query metadata
  • Affected rows and result counts

Configuration Options

// config/chronotrace.php
'database' => [
    'enabled' => env('CHRONOTRACE_CAPTURE_DATABASE', true),
    
    // Query details
    'include_bindings' => true,
    'include_explain_plan' => false, // For MySQL EXPLAIN
    'max_query_length' => 10000,    // Truncate very long queries
    
    // Performance filtering
    'slow_query_threshold' => 100,  // Only capture queries >100ms
    'capture_all_queries' => true,  // Set false to only capture slow queries
    
    // Security and filtering
    'excluded_tables' => [
        'sessions',
        'cache',
        'telescope_*',
        'chronotrace_*',
    ],
    
    'excluded_query_types' => [
        // 'select',  // Uncomment to ignore SELECT queries
        // 'insert',
        // 'update',
        // 'delete',
    ],
    
    // Connection filtering
    'included_connections' => [
        'mysql',
        'pgsql',
        // Only capture from these connections
    ],
    
    // Scrubbing
    'scrub_bindings' => true,
    'scrub_patterns' => [
        '/\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b/', // Credit cards
        '/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/', // Emails
    ],
],

Example Database Event

{
  "type": "database",
  "timestamp": "2024-08-06T14:30:15.125Z",
  "offset_ms": 2,
  "connection": "mysql",
  "sql": "SELECT id, name, email FROM users WHERE active = ? AND created_at > ?",
  "bindings": [true, "2024-01-01 00:00:00"],
  "duration_ms": 15,
  "rows_returned": 150,
  "memory_used_mb": 2.3,
  "query_type": "select",
  "affected_table": "users"
}

Advanced Database Filtering

// Conditional database capturing
'database' => [
    'conditional_capture' => function ($query) {
        // Only capture queries from specific models
        if (str_contains($query->sql, 'FROM orders')) {
            return true;
        }
        
        // Always capture slow queries
        if ($query->time > 100) {
            return true;
        }
        
        // Skip routine queries
        if (str_contains($query->sql, 'sessions') || 
            str_contains($query->sql, 'cache')) {
            return false;
        }
        
        return true;
    },
],

πŸ’Ύ Cache Event Capturing

What's Captured

Cache events include:

  • Cache operations (get, set, forget, flush)
  • Hit/miss status and cache store information
  • TTL values and cache sizes
  • Cache keys and operation results

Configuration Options

// config/chronotrace.php
'cache' => [
    'enabled' => env('CHRONOTRACE_CAPTURE_CACHE', true),
    
    // Data inclusion
    'include_values' => false,        // Don't store actual cache values (can be large)
    'include_hit_miss' => true,       // Track cache efficiency
    'max_key_length' => 255,          // Truncate long cache keys
    'max_value_size' => 1024,         // Don't capture values >1KB
    
    // Performance filtering
    'slow_operation_threshold' => 50, // Only capture operations >50ms
    'capture_all_operations' => true, // Set false for slow operations only
    
    // Key filtering
    'excluded_key_patterns' => [
        'session:*',
        'telescope:*',
        'chronotrace:*',
        'temp:*',
    ],
    
    'included_stores' => [
        'redis',
        'memcached',
        // Only capture from these stores
    ],
    
    // Operation filtering
    'excluded_operations' => [
        // 'get',     // Uncomment to ignore GET operations
        // 'set',
        // 'forget',
    ],
],

Example Cache Event

{
  "type": "cache",
  "timestamp": "2024-08-06T14:30:15.135Z",
  "offset_ms": 12,
  "operation": "get",
  "key": "user:123:profile",
  "store": "redis",
  "result": "hit",
  "ttl_seconds": 3600,
  "duration_ms": 2,
  "value_size_bytes": 1024
}

🌐 HTTP Event Capturing

What's Captured

HTTP events include:

  • External API calls with full request/response data
  • Request/response headers and payloads
  • Connection timing and DNS resolution
  • Error details and retry attempts

Configuration Options

// config/chronotrace.php
'http' => [
    'enabled' => env('CHRONOTRACE_CAPTURE_HTTP', true),
    
    // Request/Response data
    'include_request_headers' => true,
    'include_request_body' => true,
    'include_response_headers' => true,
    'include_response_body' => true,
    
    // Size limits
    'max_request_body_size' => 64 * 1024,   // 64KB
    'max_response_body_size' => 128 * 1024, // 128KB
    
    // Performance filtering
    'slow_request_threshold' => 1000,       // Only capture requests >1s
    'capture_all_requests' => true,         // Set false for slow requests only
    
    // URL filtering
    'excluded_hosts' => [
        'localhost',
        '127.0.0.1',
        'internal.company.com',
    ],
    
    'excluded_url_patterns' => [
        'https://cdn.example.com/*',
        '*/health-check',
        '*/ping',
    ],
    
    // Status filtering
    'capture_successful_requests' => true,
    'capture_failed_requests' => true,
    'excluded_status_codes' => [
        // 404,  // Uncomment to ignore 404s
    ],
    
    // Security
    'scrub_request_headers' => [
        'Authorization',
        'X-API-Key',
        'Cookie',
    ],
    'scrub_response_headers' => [
        'Set-Cookie',
    ],
],

Example HTTP Event

{
  "type": "http",
  "timestamp": "2024-08-06T14:30:15.200Z",
  "offset_ms": 77,
  "method": "POST",
  "url": "https://api.stripe.com/v1/charges",
  "request_headers": {
    "Content-Type": "application/x-www-form-urlencoded",
    "Authorization": "[REDACTED]"
  },
  "request_body": "amount=2999&currency=usd&source=tok_[REDACTED]",
  "response_status": 200,
  "response_headers": {
    "Content-Type": "application/json"
  },
  "response_body": "{\"id\": \"ch_[REDACTED]\", \"status\": \"succeeded\"}",
  "duration_ms": 1250,
  "connection_time_ms": 45,
  "dns_time_ms": 12
}

πŸ”„ Queue Job Event Capturing

What's Captured

Job events include:

  • Job dispatching and queue assignment
  • Job payloads and serialized data
  • Processing status and completion time
  • Failure information and retry attempts

Configuration Options

// config/chronotrace.php
'jobs' => [
    'enabled' => env('CHRONOTRACE_CAPTURE_JOBS', true),
    
    // Payload inclusion
    'include_job_payload' => true,
    'max_payload_size' => 10 * 1024,      // 10KB payload limit
    'serialize_payload' => true,           // Include serialized job data
    
    // Job filtering
    'excluded_job_classes' => [
        'Laravel\\Telescope\\*',
        'App\\Jobs\\TelemetryCollection',
        'App\\Jobs\\LogCleanup',
    ],
    
    'included_queues' => [
        'default',
        'emails',
        'payments',
        // Only capture jobs from these queues
    ],
    
    // Status filtering
    'capture_dispatched' => true,
    'capture_processing' => false,         // Can be very verbose
    'capture_completed' => true,
    'capture_failed' => true,
    
    // Performance filtering
    'slow_job_threshold' => 5000,         // Jobs taking >5s
    'capture_all_jobs' => true,
],

Example Job Event

{
  "type": "job",
  "timestamp": "2024-08-06T14:30:15.300Z",
  "offset_ms": 177,
  "action": "dispatched",
  "job_class": "App\\Jobs\\SendWelcomeEmail",
  "queue": "emails",
  "connection": "redis",
  "delay_seconds": 0,
  "max_tries": 3,
  "timeout": 60,
  "payload": {
    "user_id": 123,
    "template": "welcome",
    "locale": "en"
  },
  "job_id": "job_abc123def456"
}

πŸŽͺ Laravel Event Capturing

What's Captured

Laravel events include:

  • Built-in Laravel events (eloquent, auth, etc.)
  • Custom application events
  • Event listeners and their execution
  • Event payload data

Configuration Options

// config/chronotrace.php
'events' => [
    'enabled' => env('CHRONOTRACE_CAPTURE_EVENTS', false), // Disabled by default
    
    // Event filtering
    'included_event_classes' => [
        'App\\Events\\*',              // Only custom events
        'Illuminate\\Auth\\Events\\*', // Auth events
        // Be selective - events can be very verbose
    ],
    
    'excluded_event_classes' => [
        'Illuminate\\Log\\Events\\*',
        'Illuminate\\Database\\Events\\QueryExecuted', // Already captured in DB events
    ],
    
    // Payload handling
    'include_event_payload' => true,
    'max_payload_size' => 5 * 1024,        // 5KB limit
    'serialize_objects' => false,           // Don't serialize complex objects
    
    // Listener tracking
    'track_listeners' => true,
    'track_listener_performance' => true,
],

Example Event

{
  "type": "event",
  "timestamp": "2024-08-06T14:30:15.180Z",
  "offset_ms": 57,
  "event_class": "App\\Events\\UserRegistered",
  "payload": {
    "user_id": 123,
    "email": "[REDACTED]",
    "registration_source": "web"
  },
  "listeners": [
    {
      "class": "App\\Listeners\\SendWelcomeEmail",
      "duration_ms": 15
    },
    {
      "class": "App\\Listeners\\UpdateAnalytics",
      "duration_ms": 3
    }
  ]
}

πŸ“ Log Event Capturing

What's Captured

Log events include:

  • Application log entries with context
  • Log levels and channels
  • Exception details and stack traces
  • Log context data

Configuration Options

// config/chronotrace.php
'logs' => [
    'enabled' => env('CHRONOTRACE_CAPTURE_LOGS', false), // Disabled by default
    
    // Level filtering
    'min_log_level' => 'warning',          // Only warning and above
    'included_levels' => [
        'emergency', 'alert', 'critical', 'error', 'warning'
        // 'notice', 'info', 'debug'      // Uncomment for verbose logging
    ],
    
    // Channel filtering
    'included_channels' => [
        'single',
        'daily',
        // Don't include every channel to avoid noise
    ],
    
    'excluded_channels' => [
        'chronotrace',                     // Don't capture own logs
    ],
    
    // Content filtering
    'include_context' => true,
    'include_stack_trace' => true,
    'max_message_length' => 1000,
    'max_context_size' => 2 * 1024,       // 2KB context limit
],

πŸŽ›οΈ Environment-Specific Configuration

Development Environment

// Capture everything for comprehensive debugging
'capture' => [
    'database' => true,
    'cache' => true,
    'http' => true,
    'jobs' => true,
    'events' => true,     // Enable for detailed debugging
    'logs' => true,       // Enable for full context
],

Staging Environment

// Balanced approach for testing
'capture' => [
    'database' => true,
    'cache' => false,     // Reduce noise
    'http' => true,
    'jobs' => true,
    'events' => false,    // Too verbose for staging
    'logs' => false,      // Use dedicated log monitoring
],

Production Environment

// Minimal, performance-focused capture
'capture' => [
    'database' => true,   // Essential for debugging
    'cache' => false,     // Usually not needed in production
    'http' => true,       // Critical for API issues
    'jobs' => true,       // Important for async processing
    'events' => false,    // Too verbose
    'logs' => false,      // Use dedicated logging
],

πŸ”§ Dynamic Event Capturing

Runtime Configuration

// Temporarily enable specific events
use Grazulex\LaravelChronotrace\Facades\ChronoTrace;

// Enable cache events for this request
ChronoTrace::enableCacheCapture();

// Disable database events temporarily
ChronoTrace::disableDatabaseCapture();

// Enable verbose logging for debugging
ChronoTrace::enableVerboseCapture(['events', 'logs']);

Conditional Capturing

// Capture events based on request context
'conditional_capture' => [
    'database' => function ($request) {
        // Only capture DB events for admin routes
        return $request->is('admin/*');
    },
    
    'cache' => function ($request) {
        // Capture cache events for API routes
        return $request->is('api/*');
    },
    
    'events' => function ($request) {
        // Enable events for specific users
        return $request->user()?->hasRole('developer');
    },
],

User-Based Capturing

// Different capture settings per user type
'user_based_capture' => [
    'admin' => ['database', 'cache', 'http', 'jobs', 'events'],
    'developer' => ['database', 'http', 'jobs'],
    'regular' => ['database', 'http'],
],

πŸ“Š Performance Impact Analysis

Capture Overhead by Event Type

Event Type CPU Overhead Memory Overhead Storage per Event
Database ~0.1ms ~1KB ~500 bytes
Cache ~0.05ms ~0.5KB ~200 bytes
HTTP ~0.2ms ~5KB ~2KB
Jobs ~0.1ms ~2KB ~800 bytes
Events ~0.5ms ~3KB ~1KB
Logs ~1ms ~4KB ~1.5KB

Optimization Recommendations

// High-traffic production optimization
'performance_optimized' => [
    'capture' => [
        'database' => true,
        'cache' => false,        // Disable for high-traffic
        'http' => true,
        'jobs' => true,
        'events' => false,       // Disable for performance
        'logs' => false,         // Use external logging
    ],
    
    'database' => [
        'slow_query_threshold' => 100,  // Only slow queries
        'capture_all_queries' => false,
    ],
    
    'http' => [
        'slow_request_threshold' => 1000, // Only slow requests
        'capture_all_requests' => false,
    ],
],

🎯 Best Practices

1. Start Minimal, Add as Needed

Begin with essential events:

'capture' => [
    'database' => true,   // Always useful
    'http' => true,       // Critical for APIs
    'jobs' => true,       // Important for async
    'cache' => false,     // Add when debugging cache
    'events' => false,    // Add when debugging events
    'logs' => false,      // Use external tools
],

2. Use Environment-Specific Settings

Different environments need different capture levels:

  • Development: Verbose capture for understanding
  • Staging: Balanced capture for testing
  • Production: Minimal capture for performance

3. Monitor Storage Usage

Track storage growth by event type:

php artisan chronotrace:storage-breakdown --by-event-type

4. Adjust Based on Debugging Needs

Enable specific events when debugging specific issues:

// Debugging cache issues
CHRONOTRACE_CAPTURE_CACHE=true

// Debugging event-driven features
CHRONOTRACE_CAPTURE_EVENTS=true

// Debugging background jobs
CHRONOTRACE_CAPTURE_JOBS=true

πŸ“š Related Documentation


Configure event capturing to match your debugging needs! Start with the essentials and add more detailed capture as needed for specific debugging scenarios.

Clone this wiki locally