3.8. Debug Mode and Testing

Order Daemon includes debugging and testing tools to help developers and store owners troubleshoot issues, test configurations, and monitor plugin behavior.

Quick Start

Enable debug mode to see detailed execution information:

Recommended Method (Insight Dashboard):

  1. Go to WooCommerce → Insight Dashboard
  2. Click the gear icon in the filter pane header to open Settings
  3. Expand “Debug Settings” section
  4. Check “Enable Global Debug Mode”

Alternative Method (wp-config.php):

// Add to wp-config.php
define('ODCM_DEBUG', true);

Generate test logs for demonstration:

  1. Go to WooCommerce → Insight Dashboard
  2. Click the gear icon in the filter pane header to open Settings
  3. Expand “Debug Settings” section
  4. Click “Generate Sample Logs”

Overview

The plugin provides debugging and testing functionality:

  • Debug Mode: Enhanced logging with detailed execution information
  • Test Log Generation: Create sample audit entries for testing and demonstration
  • Log Filtering: Show or hide test entries in the audit trail
  • Development Integration: Works with WordPress debug settings

These tools help with:

  • Troubleshooting rule execution issues
  • Testing new configurations safely
  • Monitoring plugin performance
  • Training team members
  • Demonstrating plugin capabilities

Debug Mode Configuration

Understanding ODCM_DEBUG vs WP_DEBUG

Order Daemon uses two debug settings that work independently or together:

WordPress Debug (WP_DEBUG)

Standard WordPress debugging that affects the entire site:

// In wp-config.php
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);

Order Daemon Debug (ODCM_DEBUG)

Plugin-specific debugging that can be enabled independently:

// In wp-config.php - Option 1: Enable with WordPress debug
define('WP_DEBUG', true);
define('ODCM_DEBUG', true);

// Option 2: Enable independently (production-safe)
define('ODCM_DEBUG', true);

Debug Mode Behaviors

SettingWP_DEBUGODCM_DEBUGResult
ProductionfalsefalseStandard logging only
Plugin DebugfalsetrueOrder Daemon verbose logging
Full DebugtruetrueComplete debugging (recommended for development)
WordPress DebugtruefalseWordPress debugging without plugin verbosity

Enabling Debug Mode

Method 1: wp-config.php (Recommended)

Add to your wp-config.php file before the “stop editing” comment:

// Enable Order Daemon debug mode
define('ODCM_DEBUG', true);

// Optional: Enable WordPress debugging too
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false); // Don't show errors on frontend

Method 2: Plugin File (Temporary)

For temporary debugging, you can add to your theme’s functions.php:

// Temporary debug mode - remove after testing
if (!defined('ODCM_DEBUG')) {
    define('ODCM_DEBUG', true);
}

⚠️ Security Note: Always disable debug mode on production sites after troubleshooting.

Debug Logging System

Log Categories

When debug mode is enabled, the plugin logs events in different categories:

Core Events (Always Logged)

  • Order completion attempts
  • Rule matching and execution
  • Error conditions
  • System operations

Debug Events (ODCM_DEBUG Only)

  • Detailed execution flow
  • Condition evaluation steps
  • Action execution details
  • Database query information
  • Performance metrics

Premium Events (Always Logged)

  • Advanced feature usage
  • Premium condition matching
  • Custom email sending
  • Bulk operations

Debug Event Examples

With ODCM_DEBUG enabled, you’ll see detailed entries like:

[DEBUG] Starting order check process for order #1234
[DEBUG] Evaluating rule "Complete Virtual Products" for order #1234
[DEBUG] Condition "product_type_virtual" for order #1234: PASSED
[DEBUG] Executing action "mark_completed" for order #1234
[INFO] Order #1234 completed successfully

Viewing Debug Logs

Debug events appear in multiple interfaces:

  1. Insight Dashboard (WooCommerce → Insight Dashboard) – Recommended
    • Real-time Updates: Debug events appear automatically every 5 seconds
    • Advanced Filtering: Filter by debug status, event types, and date ranges
    • Component Rendering: Complex debug payloads rendered with specialized components
    • Persistent Preferences: Your debug filter preferences are saved and restored
    • Expandable Details: Click any debug entry to see full context and stack traces
    • Performance Monitoring: Real-time performance metrics and memory usage
  2. Traditional Audit Trail (Admin → Order Daemon)
    • Filter by “Debug” status to see debug events
    • Use date filters to focus on recent debugging sessions
    • Component-based rendering for complex debug data
  3. WordPress Debug Log (if WP_DEBUG_LOG is enabled)
    • Location: /wp-content/debug.log
    • Contains error_log() output from the plugin
  4. WP-CLI (Premium feature for command-line access) wp odcm log list --status=debug --limit=50

Insight Dashboard Debug Features

The modern Insight Dashboard provides enhanced debugging capabilities:

Debug Event Filtering:

  • Include Debug Logs: Toggle checkbox to show/hide debug entries (preference saved automatically)
  • Include Test Logs: Toggle checkbox to show/hide test entries (preference saved automatically)
  • Real-time Monitoring: Watch debug events appear as they happen with auto-refresh
  • Performance Tracking: Monitor execution times and memory usage in detail components

Debug Settings Panel:
Access via the gear icon in the filter pane header:

  • Enable Global Debug Mode: Toggle ODCM_DEBUG constant server-wide (use with caution)
  • Add Debug Info to Order Notes: Include detailed product information in order notes when rules don’t match
  • Generate Sample Logs: Create comprehensive sample log entries for testing component rendering

Debug Component Rendering:

  • Syntax Highlighting: Code blocks with Prism.js highlighting for PHP, JSON, SQL
  • Performance Metrics: Execution time, memory usage, and database query counts
  • Error Details: Comprehensive error information with context and stack traces
  • System Information: Environment details and configuration data

Persistent Debug Preferences:

  • Debug Visibility: Whether debug logs are included in the stream (saved to localStorage)
  • Test Log Visibility: Whether test logs are included in the stream (saved to localStorage)
  • Detail Pane Expansion: Expanded view for easier code inspection (saved to localStorage)
  • Auto-Refresh Settings: Configure update frequency for debug sessions (saved to localStorage)
  • Settings Accordion State: Which settings sections are expanded (saved to localStorage)

Test Log Generation

Admin Interface Method

The easiest way to generate test logs for demonstration or testing:

Step 1: Access Developer Tools

  1. Navigate to WooCommerce → Order Daemon → Settings
  2. Click the “Developer Tools” tab
  3. Scroll to the “Sample Log Generation” section

Step 2: Generate Sample Logs

  1. Click “Generate Sample Logs” button
  2. The system will create comprehensive test entries
  3. Sample logs appear in the Audit Trail within seconds

Sample Log Types Generated

  • Order completion events (success/error)
  • Rule matching scenarios
  • Condition evaluation results
  • Action execution outcomes
  • System operations
  • Debug events (if ODCM_DEBUG is enabled)

WP-CLI Method

For automated testing or bulk generation:

# Generate 15 sample log entries (default)
wp odcm log generate-sample

# Generate specific number of entries
wp odcm log generate-sample --count=30

# Generate samples and view immediately
wp odcm log generate-sample --count=10 && wp odcm log list --limit=10

Security Requirement: WP-CLI sample generation requires WP_DEBUG to be enabled for security.

Test Log Characteristics

Generated test logs include:

  • Realistic Data: Uses actual order IDs and realistic scenarios
  • Variety: Mix of success, error, warning, and info events
  • Test Flagging: Marked as test entries in the database
  • Comprehensive Coverage: Represents all major plugin operations

Managing Test Logs

Filtering Test Logs in Admin

The Audit Trail interface includes a test log filter:

Show/Hide Test Logs

  1. Go to WooCommerce → Order Daemon
  2. Look for the “Include Test Logs” checkbox in the settings pane
    • Checked: Shows both real and test log entries
    • Unchecked: Shows only real operational logs (default)

Visual Identification

Test logs are marked with:

  • [TEST] prefix in the summary
  • Special filtering options

Cleaning Up Test Logs

Via WP-CLI

# Delete all test logs
wp odcm log bulk-delete --type=test --yes

# Delete test logs older than 7 days
wp odcm log bulk-delete --type=test --before="2025-01-12" --yes

# Preview what would be deleted (dry run)
wp odcm log bulk-delete --type=test --dry-run

Via Database (Advanced Users)

-- Delete all test log entries
DELETE FROM wp_odcm_audit_logs WHERE is_test = 1;

-- Delete test logs older than 30 days
DELETE FROM wp_odcm_audit_logs
WHERE is_test = 1
AND timestamp < DATE_SUB(NOW(), INTERVAL 30 DAY);

Troubleshooting with Debug Mode

Common Debugging Scenarios

Scenario 1: Rules Not Triggering

Problem: Orders aren’t being completed automatically

Debug Steps:

  1. Enable ODCM_DEBUG
  2. Process a test order manually
  3. Check audit trail for debug events: [DEBUG] Starting order check process for order #1234 [INFO] No completion rules found for order #1234
  4. Solution: Create or activate completion rules

Scenario 2: Rules Triggering But Failing

Problem: Rules match but orders don’t complete

Debug Steps:

  1. Look for debug events showing rule evaluation: [DEBUG] Evaluating rule "Complete Virtual Products" for order #1234 [DEBUG] Condition "product_type_virtual" for order #1234: FAILED [INFO] Order #1234 skipped rule "Complete Virtual Products": Condition not met
  2. Solution: Adjust rule conditions or check order properties

Scenario 3: Performance Issues

Problem: Plugin seems slow or causes timeouts

Debug Steps:

  1. Enable both WP_DEBUG and ODCM_DEBUG
  2. Monitor debug log for performance indicators
  3. Look for database query events: [DEBUG] Database query executed: SELECT * FROM wp_posts WHERE... (0.045s)
  4. Solution: Optimize rules or contact support for performance tuning

Debug Log Analysis

Reading Debug Event Flow

[DEBUG] Starting order check process for order #1234
[DEBUG] Evaluating rule "Complete Virtual Products" for order #1234
[DEBUG] Condition "product_type_virtual" for order #1234: PASSED
[DEBUG] Condition "order_total_above" for order #1234: PASSED
[DEBUG] Executing action "mark_completed" for order #1234
[INFO] Order #1234 completed successfully

This flow shows:

  1. ✅ Order processing started
  2. ✅ Rule found and evaluated
  3. ✅ All conditions passed
  4. ✅ Action executed successfully
  5. ✅ Order completed

Identifying Issues

[DEBUG] Starting order check process for order #1234
[ERROR] Order #1234 could not be loaded or is invalid

This indicates:

  • ❌ Order object is corrupted or doesn’t exist
  • Solution: Check order status in WooCommerce admin

Development Environment Integration

Local Development Setup

Recommended wp-config.php for Development

// Development environment detection
if (defined('WP_LOCAL_DEV') || $_SERVER['HTTP_HOST'] === 'localhost') {
    // WordPress debugging
    define('WP_DEBUG', true);
    define('WP_DEBUG_LOG', true);
    define('WP_DEBUG_DISPLAY', true);
    define('SCRIPT_DEBUG', true);
    // Order Daemon debugging
    define('ODCM_DEBUG', true);
    // Disable caching
    define('WP_CACHE', false);
}

Staging Environment Setup

// Staging environment - limited debugging
if (strpos($_SERVER['HTTP_HOST'], 'staging') !== false) {
    define('WP_DEBUG', true);
    define('WP_DEBUG_LOG', true);
    define('WP_DEBUG_DISPLAY', false); // Don't show errors to visitors
    define('ODCM_DEBUG', true);
}

Testing Workflows

Rule Development Workflow

  1. Enable Debug Mode define('ODCM_DEBUG', true);
  2. Create Test Orders
    • Use WooCommerce’s built-in test data
    • Or create orders manually with specific properties
  3. Generate Test Logs wp odcm log generate-sample --count=20
  4. Test Rule Logic
    • Create/modify completion rules
    • Process test orders
    • Monitor debug events in audit trail
  5. Validate Results wp odcm log list --since="2025-01-19" --status=debug

Performance Testing

  1. Enable Full Debugging define('WP_DEBUG', true); define('ODCM_DEBUG', true);
  2. Generate Load # Generate many test logs to simulate activity wp odcm log generate-sample --count=100
  3. Monitor Performance
    • Check debug.log for slow queries
    • Monitor audit trail load times
    • Test with large datasets

Testing Best Practices

Safe Testing Approach

  1. Use Test Logs: Always generate test logs instead of testing with real orders
  2. Enable Debug Mode: Use ODCM_DEBUG to see detailed execution flow
  3. Test in Staging: Never test on production sites
  4. Clean Up: Remove test logs after testing

Common Testing Scenarios

Testing Rule Logic

  • Create a test order manually in WooCommerce admin
  • Then trigger rule evaluation to see debug output

Testing Error Handling

  • Generate test logs with various error scenarios
  • Monitor how the plugin handles different edge cases
  • Verify error logging works correctly

Best Practices

Security Considerations

Production Safety

  • Never enable debug mode on production sites
  • Use staging environments for debugging
  • Remove debug constants after troubleshooting
  • Monitor log file sizes to prevent disk space issues

Sensitive Data Protection

// Good: Log without sensitive data
odcm_log_custom_event(
    'Payment processed for order #' . $order_id,
    ['order_total' => $order->get_total()],
    $order_id,
    'success'
);

// Bad: Don't log sensitive payment details
// odcm_log_custom_event('Payment: ' . $credit_card_number, ...);

Performance Considerations

Debug Mode Impact

  • Increased Logging: More database writes
  • Larger Log Files: Monitor disk space usage
  • Slower Execution: Additional processing overhead

Optimization Tips

// Conditional debug logging
if (defined('ODCM_DEBUG') && ODCM_DEBUG) {
    odcm_log_registered_event('detailed_debug_event', $extensive_data);
}

// Use appropriate log levels
odcm_log_custom_event('Minor info', [], $order_id, 'info');     // Low priority
odcm_log_custom_event('Critical error', [], $order_id, 'error'); // High priority

Log Management

Regular Cleanup

# Weekly cleanup script
#!/bin/bash

# Remove test logs older than 7 days
wp odcm log bulk-delete --type=test --before="$(date -d '7 days ago' +%Y-%m-%d)" --yes

# Remove debug logs older than 30 days
wp odcm log bulk-delete --status=debug --before="$(date -d '30 days ago' +%Y-%m-%d)" --yes

# Archive old logs before deletion
wp odcm log export --until="$(date -d '90 days ago' +%Y-%m-%d)" --output="archive-$(date +%Y%m).json"

Monitoring and Alerts

# Check for recent errors
ERROR_COUNT=$(wp odcm log list --status=error --since="$(date -d '1 hour ago' +%Y-%m-%d\ %H:%M:%S)" --format=count)

if [ "$ERROR_COUNT" -gt 5 ]; then
    echo "Alert: $ERROR_COUNT errors in the last hour"
    # Send notification to monitoring system
fi

Troubleshooting Common Issues

Debug Mode Not Working

Issue: ODCM_DEBUG enabled but no debug events appear

Solutions:

  1. Check constant definition: // Verify in wp-config.php var_dump(defined('ODCM_DEBUG') && ODCM_DEBUG); // Should output: bool(true)
  2. Clear caches:
    • Object cache (Redis/Memcached)
    • Page cache (WP Rocket, LiteSpeed, etc.)
    • Opcode cache (restart PHP-FPM)
  3. Check plugin activation: wp plugin is-active order-daemon/order-daemon.php Reactivate the plugin, if necessary.

Test Logs Not Generating

Issue: Sample log generation fails

Solutions:

  1. Check permissions:
    • User must have manage_woocommerce capability
    • Verify nonce is working correctly
  2. Check Action Scheduler: wp action-scheduler status
  3. Manual generation: // Direct function call for testing OrderDaemon\CompletionManager\Admin\AuditTrailAdmin::generate_sample_logs(10);

Performance Issues

Issue: Debug mode causes site slowdown

Solutions:

  1. Reduce debug verbosity: // Temporary: Disable debug for specific operations remove_action('odcm_debug_event', 'odcm_log_debug_event');
  2. Optimize database: -- Add index for better performance ALTER TABLE wp_odcm_audit_logs ADD INDEX idx_debug_status (status, timestamp);
  3. Use selective debugging: // Only debug specific order IDs if (defined('ODCM_DEBUG_ORDER') && $order_id == ODCM_DEBUG_ORDER) { odcm_log_registered_event('debug_event', $data); }

Advanced Usage

Custom Debug Logging

You can create custom debug events in your own code:

// Log custom debug information
if (defined('ODCM_DEBUG') && ODCM_DEBUG) {
    odcm_log_custom_event(
        'Custom integration debug info',
        [
            'operation' => 'customer_sync',
            'execution_time_ms' => 1250,
            'memory_usage' => memory_get_usage(true)
        ],
        $order_id,
        'debug'
    );
}

Monitoring Plugin Health

Use the audit trail to monitor plugin health:

  • Error Patterns: Look for recurring error types
  • Performance Trends: Monitor execution times
  • Rule Effectiveness: Track rule success rates
  • System Load: Watch for performance warnings

Conclusion

The debug mode and testing features in Order Daemon for WooCommerce provide comprehensive tools for troubleshooting, testing, and monitoring plugin behavior. By understanding and utilizing these features effectively, you can:

  • Quickly diagnose issues with detailed debug logging
  • Test configurations safely using sample data
  • Monitor plugin performance in development and staging environments
  • Maintain clean audit trails by managing test data appropriately

Remember to always disable debug mode on production sites and follow security best practices when handling log data. The testing tools are designed to be safe and non-intrusive, making them valuable for both development and user training scenarios.

For additional support with debugging complex issues, consult the Troubleshooting Guide.

Was this article helpful?

  • Loading...
Table of Contents
  • Loading...