3.6 Advanced Logging API

Order Daemon provides a comprehensive audit logging system for tracking order automation events, custom integrations, and system operations. The system uses asynchronous processing and a dual-table architecture for optimal performance.

Quick Start

Basic Custom Event Logging

// Simple event
odcm_log_custom_event('Integration completed successfully');

// Event with order association
odcm_log_custom_event(
    'Customer data synchronized',
    ['sync_time_ms' => 1200],
    $order_id,
    'success'
);

// Error logging with context
odcm_log_custom_event(
    'API call failed',
    [
        'endpoint' => 'https://api.example.com/customers',
        'error_code' => 'TIMEOUT',
        'response_time_ms' => 5000
    ],
    $order_id,
    'error'
);

Registry-Based Events (Internal)

// Internal plugin events using predefined templates
odcm_log_registered_event('order_completed', [
    'order_id' => 123,
    'summary_args' => [123], // For sprintf template
    'details' => ['completion_time_ms' => 240]
]);

Core Architecture

Asynchronous Processing

All logging operations are queued through WordPress Action Scheduler to prevent blocking user-facing requests:

  • Events are immediately queued via odcm_log_event()
  • Background processing handles database writes
  • No performance impact on checkout or admin operations

Dual-Table Design

Primary Table: wp_odcm_audit_log

  • Fast queries and filtering
  • Essential fields: id, timestamp, status, summary, event_type, order_id
  • Optional fields: payload_id, process_id, log_category, is_test, source

Payload Table: wp_odcm_audit_log_payloads

  • Detailed data storage
  • JSON-encoded payloads with narrative components
  • Linked via payload_id foreign key

Logging APIs

1. Public Custom Event API

Function: odcm_log_custom_event()

odcm_log_custom_event(
    string $summary,           // Required: Human-readable description
    ?array $payload = null,    // Optional: Structured data
    ?int $order_id = null,     // Optional: WooCommerce order ID
    string $status = 'info',   // Optional: Event status
    ?string $event_type = null // Optional: Machine-readable type
);

Available Statuses:

  • success – Successful operations
  • error – Failures and exceptions
  • warning – Non-critical issues
  • info – General information (default)
  • notice – Important notifications
  • debug – Development information

Example Usage:

// Integration success
odcm_log_custom_event(
    'MailChimp subscriber updated',
    [
        'subscriber_email' => 'customer@example.com',
        'list_id' => 'abc123',
        'tags_added' => ['customer', 'vip']
    ],
    $order_id,
    'success',
    'mailchimp_sync'
);

// Error with context
odcm_log_custom_event(
    'Payment gateway webhook failed',
    [
        'gateway' => 'stripe',
        'webhook_id' => 'whsec_123',
        'error_message' => 'Invalid signature',
        'retry_count' => 3
    ],
    $order_id,
    'error',
    'webhook_failure'
);

2. Registry-Based Events (Internal)

Function: odcm_log_registered_event()

odcm_log_registered_event(
    string $event_slug,        // Predefined event identifier
    array $context_data = []   // Context including order_id, summary_args
);

Used internally by the plugin for consistent event logging with predefined templates.

3. Universal API (Advanced)

Function: odcm_log_event()

odcm_log_event([
    'canonical' => true,
    'summary' => 'External sync completed',
    'event_type' => 'external_api_sync',
    'status' => 'success',
    'data' => [
        'order_id' => 456,
        'details' => $payload_data,
        'log_category' => 'custom',
        'is_test' => false
    ]
]);

Provides full control over all logging fields for advanced integrations.

Querying Audit Logs

Basic Queries

global $wpdb;

// Get recent logs for an order
$order_logs = $wpdb->get_results($wpdb->prepare(
    "SELECT l.id, l.timestamp, l.status, l.summary, l.event_type, p.payload
     FROM {$wpdb->prefix}odcm_audit_log l
     LEFT JOIN {$wpdb->prefix}odcm_audit_log_payloads p ON l.payload_id = p.id
     WHERE l.order_id = %d
     ORDER BY l.timestamp DESC
     LIMIT 20",
    $order_id
));

// Get recent errors
$recent_errors = $wpdb->get_results(
    "SELECT id, timestamp, order_id, event_type, summary
     FROM {$wpdb->prefix}odcm_audit_log
     WHERE status = 'error'
     ORDER BY timestamp DESC
     LIMIT 10"
);

Performance Tips

  • Filter on indexed columns first: status, timestamp, order_id, event_type
  • Join to payloads table only when detailed data is needed
  • Always use LIMIT clauses for dashboard queries
  • Use $wpdb->prepare() for all dynamic queries

Integration Examples

CRM Synchronization

function sync_customer_to_crm($order_id) {
    $order = wc_get_order($order_id);
    
    try {
        $response = call_crm_api($order->get_billing_email());
        
        odcm_log_custom_event(
            "Customer synchronized to CRM",
            [
                'crm_customer_id' => $response['customer_id'],
                'sync_duration_ms' => $response['duration'],
                'fields_updated' => ['email', 'name', 'phone']
            ],
            $order_id,
            'success',
            'crm_sync'
        );
        
    } catch (Exception $e) {
        odcm_log_custom_event(
            "CRM sync failed: " . $e->getMessage(),
            [
                'error_code' => $e->getCode(),
                'customer_email' => $order->get_billing_email(),
                'retry_count' => get_post_meta($order_id, '_crm_retry_count', true)
            ],
            $order_id,
            'error',
            'crm_sync_error'
        );
    }
}

Webhook Integration

function handle_payment_webhook($webhook_data) {
    $order_id = $webhook_data['order_id'];
    
    odcm_log_custom_event(
        "Payment webhook received",
        [
            'webhook_type' => $webhook_data['type'],
            'payment_status' => $webhook_data['payment']['status'],
            'amount' => $webhook_data['payment']['amount'],
            'gateway' => 'stripe',
            'webhook_id' => $webhook_data['id']
        ],
        $order_id,
        'info',
        'payment_webhook'
    );
    
    // Process webhook...
}

Security and Privacy

Automatic Sanitization

All payload data is automatically sanitized before storage:

// Sensitive data is automatically redacted
$payload = [
    'api_key' => 'sk_live_123456',        // Becomes: '***REDACTED***'
    'password' => 'user_password',        // Becomes: '***REDACTED***'
    'customer_email' => 'john@example.com', // Becomes: 'j***@example.com'
    'safe_data' => 'This is preserved'
];

Best Practices

// DO: Log business metrics and operational data
odcm_log_custom_event(
    'Order processing completed',
    [
        'processing_time_ms' => 1200,
        'items_count' => 3,
        'total_amount' => 99.99
    ],
    $order_id,
    'success'
);

// DON'T: Log sensitive customer data
odcm_log_custom_event(
    'Customer data processed',
    [
        'credit_card_number' => '4111111111111111', // Never do this
        'ssn' => '123-45-6789'                      // Never do this
    ],
    $order_id
);

Hook Integration

The logging system fires WordPress actions for integration:

// Listen for new audit log entries
add_action('odcm_audit_log_recorded', function($log_id, $log_data) {
    if ($log_data['status'] === 'error') {
        // Send alert to monitoring system
        send_error_alert($log_data);
    }
});

Event Type Conventions

Use consistent naming patterns for event types:

  • Integration events: {service}_{action} (e.g., mailchimp_sync, crm_update)
  • Error events: {system}_{error_type} (e.g., webhook_failure, api_timeout)
  • System events: {category}_{event} (e.g., performance_warning, security_alert)

Testing and Development

Test Mode

Use the is_test parameter to mark development/testing events:

odcm_log_custom_event(
    'Test integration event',
    ['test_data' => true],
    null,
    'info',
    'test_event',
    true  // is_test flag
);

Test events can be filtered out in production dashboards.

Debug Logging

Debug events are only logged when ODCM_DEBUG is enabled:

// Only logged if ODCM_DEBUG is true
odcm_log_custom_event(
    'Debug: Processing step completed',
    ['step' => 'validation', 'result' => 'pass'],
    $order_id,
    'debug'
);

Was this article helpful?

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