# Error Logging in FlxWoo

## Architecture Overview

FlxWoo uses **different error logging strategies** for its two components:

| Component | Error Logging | Purpose | Location |
|-----------|---------------|---------|----------|
| **flx (Next.js)** | ✅ **Sentry** | Real-time error monitoring of SaaS infrastructure | Your server |
| **flx-woo (WordPress)** | ✅ **Logger class** | Local debugging for customer installations | Customer sites |

---

## Why Different Approaches?

### flx (Next.js Renderer) - Sentry

**Why Sentry?**
- ✅ Monitors YOUR infrastructure (centralized SaaS service)
- ✅ Real-time alerting for production errors
- ✅ Affects ALL customers - needs immediate attention
- ✅ Stack traces, performance monitoring, release tracking
- ✅ Auto-instrumentation with Next.js integration

**Configuration:**

Sentry is configured through Next.js auto-instrumentation:

```typescript
// next.config.ts in flx repository
import { withSentryConfig } from "@sentry/nextjs";

export default withSentryConfig(nextConfig, {
  org: "flxwoo",
  project: "flx",
  autoInstrumentServerFunctions: true,
  autoInstrumentMiddleware: true,
});
```

**Environment Variables** (`src/lib/config/env.ts`):
```typescript
SENTRY_ENABLED: process.env.NODE_ENV === 'production' && !!(process.env.SENTRY_DSN),
SENTRY_DSN: process.env.NEXT_PUBLIC_SENTRY_DSN || '', // Client-side
SENTRY_DSN_SERVER: process.env.SENTRY_DSN || '',     // Server-side
```

**Error Capture** (`src/app/global-error.tsx`):
```typescript
import * as Sentry from '@sentry/nextjs';

export default function GlobalError({ error }: { error: Error }) {
  useEffect(() => {
    Sentry.captureException(error);
  }, [error]);
  // ...
}
```

### flx-woo (WordPress Plugin) - Logger Class

**Why Logger instead of Sentry?**
- ✅ Lightweight (~5KB vs 17MB Sentry SDK)
- ✅ No external dependencies (plugin only 280KB!)
- ✅ WordPress standard practice (WP_DEBUG_LOG)
- ✅ Customer controls their own logs
- ✅ PII sanitization built-in
- ✅ No external API calls (privacy-friendly)

**Benefits:**
- 📦 Plugin package: **280KB** (vs 17MB+ with Sentry)
- 🔒 Privacy-compliant (no data sent to third parties)
- 🛠️ Standard WordPress debugging workflow
- 🎯 Easy customer support (just ask for debug.log)

---

## Using the Logger Class

### Enabling Logging

Add to `wp-config.php`:

```php
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);  // Don't show errors to users
```

Logs will be written to: `/wp-content/debug.log`

### Log Levels

```php
use FlxWoo\Utils\Logger;

// ERROR - For errors that prevent normal operation
Logger::error('Failed to connect to renderer', [
    'renderer_url' => $url,
    'timeout' => 5
]);

// WARNING - For issues that don't prevent operation
Logger::warning('Cart is empty', [
    'user_id' => get_current_user_id()
]);

// INFO - For important events
Logger::info('Checkout completed successfully', [
    'order_id' => 12345
]);

// DEBUG - For detailed debugging (only when WP_DEBUG is enabled)
Logger::debug('Processing cart data', [
    'item_count' => count($items)
]);
```

### Log Format

All logs use a consistent, structured format:

```
[FlxWoo] [ERROR] Failed to connect to renderer | Context: {"renderer_url":"https://...","timeout":5}
[FlxWoo] [WARNING] Cart is empty | Context: {"user_id":123}
[FlxWoo] [INFO] Checkout completed successfully | Context: {"order_id":12345}
```

**Components:**
- `[FlxWoo]` - Easy filtering with `grep "[FlxWoo]" debug.log`
- `[LEVEL]` - Error severity (ERROR, WARNING, INFO, DEBUG)
- `Message` - Human-readable description
- `Context` - JSON data for debugging

---

## Privacy & PII Sanitization

The Logger automatically sanitizes sensitive data before logging:

### Automatically Redacted

```php
Logger::error('Payment failed', [
    'email' => 'john@example.com',      // Logged as: j***@example.com
    'password' => 'secret123',          // Logged as: [REDACTED]
    'card_number' => '4111111111111111', // Logged as: [REDACTED]
    'api_key' => 'sk_live_abc123',      // Logged as: [REDACTED]
]);
```

### Sensitive Fields

Automatically masked:
- `password`, `passwd`, `pwd`
- `secret`, `token`, `api_key`, `apikey`
- `authorization`, `auth`
- `credit_card`, `card_number`, `cvv`, `cvc`
- `ssn`, `tax_id`
- Email addresses (keeps domain: `j***@example.com`)

---

## Viewing Logs

### Via SSH/Terminal

```bash
# View all FlxWoo logs
grep "[FlxWoo]" /path/to/wp-content/debug.log

# View errors only
grep "\[FlxWoo\] \[ERROR\]" /path/to/wp-content/debug.log

# View last 50 FlxWoo logs
tail -100 /path/to/wp-content/debug.log | grep "[FlxWoo]"

# Follow logs in real-time
tail -f /path/to/wp-content/debug.log | grep "[FlxWoo]"
```

### Via WordPress Plugin

Use any log viewer plugin like:
- WP Log Viewer
- Debug Log Manager
- Simple Debug Log Viewer

---

## Customer Support Workflow

When customers report errors:

1. **Ask them to enable debugging:**
   ```php
   // Add to wp-config.php
   define('WP_DEBUG', true);
   define('WP_DEBUG_LOG', true);
   define('WP_DEBUG_DISPLAY', false);
   ```

2. **Reproduce the issue**
   - The error will be logged to `wp-content/debug.log`

3. **Request the log file**
   - Ask customer to send recent entries from debug.log
   - Look for lines starting with `[FlxWoo]`

4. **Analyze with context**
   - Message tells you what happened
   - JSON context provides debugging data
   - All PII is already sanitized

---

## Comparison: Sentry vs Logger

| Feature | flx (Sentry) | flx-woo (Logger) |
|---------|--------------|------------------|
| **Error tracking** | ✅ Real-time | ✅ Debug log |
| **Package size** | N/A (your server) | ✅ 280KB |
| **External dependencies** | Sentry SDK | ❌ None |
| **Privacy** | Data sent to Sentry.io | ✅ Local only |
| **Cost** | Sentry subscription | ✅ Free |
| **Setup** | Configure DSN | ✅ WP_DEBUG_LOG |
| **Alerting** | ✅ Real-time alerts | ❌ Manual review |
| **Performance monitoring** | ✅ Yes | ❌ No |
| **Best for** | Your infrastructure | Customer installations |

---

## Production Best Practices

### For Your flx Server (Next.js)

✅ **Use Sentry** - Monitor YOUR infrastructure

Sentry is configured via environment variables and auto-instrumentation (see Configuration section above):

```bash
# Set environment variables for production
export SENTRY_DSN="your-server-side-dsn"
export NEXT_PUBLIC_SENTRY_DSN="your-client-side-dsn"

# Or in ecosystem.config.js (v2.1.0+)
env: {
  NODE_ENV: 'production',
  PORT: 3000,
  SENTRY_DSN: process.env.SENTRY_DSN || '',
  NEXT_PUBLIC_SENTRY_DSN: process.env.NEXT_PUBLIC_SENTRY_DSN || ''
}
```

**⚠️ Security Note (v2.1.0+):**
- Sentry DSNs must be set via environment variables
- Never hardcode DSNs in source code or config files
- Use PM2 ecosystem file or shell environment variables
- Rotate DSNs if accidentally committed to git

### For Customer Sites (flx-woo)

✅ **Use Logger** - Standard WordPress debugging

```php
// Only logs when WP_DEBUG_LOG is enabled
Logger::error('Error message', ['context' => 'data']);
```

### Disable Debugging in Production (Customer Sites)

By default, customers should have debugging disabled:

```php
// wp-config.php (production)
define('WP_DEBUG', false);
define('WP_DEBUG_LOG', false);
```

Enable only when troubleshooting issues.

---

## Implementation Details

### Logger Class Location

```
flx-woo/
└── src/
    └── Utils/
        └── Logger.php  (~5KB)
```

### Bootstrap Integration

The Logger is loaded early in the plugin lifecycle:

```php
// src/Bootstrap.php
require_once __DIR__ . '/Constants/Constants.php';
require_once __DIR__ . '/Utils/Logger.php';  // Loaded second
// ... other files
```

### Usage in Plugin

All FlxWoo components use Logger:

```php
// Any file in src/
use FlxWoo\Utils\Logger;

Logger::error('Message', ['context' => 'value']);
```

---

## Sentry PII Sanitization (flx Component)

The Next.js component includes a dedicated PII sanitization utility for Sentry error reporting.

### Location

```
flx/
└── src/
    └── lib/
        └── utils/
            └── sentry-sanitize.ts  (~8KB with tests)
```

### Features

The sanitization utility provides moderate PII protection while keeping debugging context:

- ✅ **Passwords & Tokens** - Completely masked as `[REDACTED]`
- ✅ **Email Addresses** - Masked local part, keeps domain (`j***@example.com`)
- ✅ **Phone Numbers** - Masked except last 4 digits (`***-***-4567`)
- ✅ **Names** - Masked except first letter (`J*** S***`)
- ✅ **Full Addresses** - Street masked, keeps city/state/country
- ✅ **Recursive Sanitization** - Handles nested objects and arrays

### Sensitive Field Patterns

Automatically redacted fields include:
- `password`, `passwd`, `pwd`
- `secret`, `token`, `api_key`, `apikey`
- `auth`, `authorization`
- `credit_card`, `card_number`, `cvv`, `cvc`
- `ssn`, `tax_id`
- `payment_method_token`, `stripe_token`, `payment_token`

### Usage

```typescript
import { sanitizeForSentry, sanitizeError } from '@/lib/utils/sentry-sanitize';

// Sanitize data before sending to Sentry
const userData = {
  email: 'john@example.com',
  password: 'secret123',
  cart: { total: 99.99 }
};
const sanitized = sanitizeForSentry(userData);
// Result: { email: 'j***@example.com', password: '[REDACTED]', cart: { total: 99.99 } }

// Sanitize errors with context
try {
  await processCheckout(data);
} catch (error) {
  const safeError = sanitizeError(error, {
    orderId: 12345,
    customer: userData  // Will be sanitized automatically
  });
  Sentry.captureException(safeError);
}
```

### Address Sanitization Example

```typescript
const address = {
  address_1: '123 Main Street',
  address_2: 'Apt 4B',
  city: 'San Francisco',
  state: 'CA',
  postcode: '94102',
  country: 'US'
};

const sanitized = sanitizeForSentry(address);
// Result: {
//   address_1: '[REDACTED]',
//   address_2: '[REDACTED]',
//   city: 'San Francisco',
//   state: 'CA',
//   postcode: '94102',
//   country: 'US'
// }
```

### Testing

Comprehensive test coverage ensures PII protection:

```bash
# Run Sentry sanitization tests
npm test sentry-sanitize

# View test file
cat src/lib/utils/__tests__/sentry-sanitize.test.ts
```

Tests cover:
- Email masking
- Phone number masking
- Name masking
- Password/token redaction
- Address sanitization
- Nested object sanitization
- Array sanitization

---

## Summary

**Use the right tool for the job:**

- 🚀 **flx (Next.js)** → Sentry (monitors YOUR infrastructure)
- 📦 **flx-woo (WordPress)** → Logger (customer debugging)

This gives you:
- ✅ Lightweight plugin (280KB)
- ✅ Real-time monitoring of your SaaS
- ✅ Privacy-compliant customer installations
- ✅ Easy support workflow
- ✅ No external dependencies in the plugin

Best of both worlds! 🎉
