# WooCommerce Plugin Logs → Sumo Logic — Investigation & Recommendation

**Status:** Recommended approach documented (acceptance criteria met)  
**Scope:** Snap Finance WooCommerce Checkout plugin (reference); applies to all Snap WooCommerce plugins  
**Sumo deployment:** Snap Merchants ART uses **US2** (`api.us2.sumologic.com`) for dashboards/monitors on Java services

---

## Executive summary

**Recommended approach:** Do **not** send logs directly from merchant WordPress sites to Sumo Logic on the checkout hot path. Instead, implement a **structured, opt-in telemetry pipeline** inside the plugin that batches **redacted, low-cardinality events** to a **Snap-operated HTTPS ingest relay**, which forwards to Sumo Logic with consistent `_sourceCategory` and metadata fields.

This minimizes merchant impact (no collector install, no outbound calls during payment), satisfies privacy/security requirements, and gives Product centralized error trends in Sumo.

| Option | Verdict |
| --- | --- |
| Merchant installs Sumo Collector | **Reject** — high friction, unsupported at scale |
| Plugin POSTs directly to Sumo HTTP Source URL per merchant | **Reject** — secrets on merchant sites, checkout latency, inconsistent categories |
| Plugin → Snap ingest relay → Sumo (opt-in, batched, redacted) | **Recommend** |
| Plugin → WooCommerce `WC_Logger` → merchant SIEM (merchant-owned) | **Optional** — document for enterprise merchants; not Snap Product telemetry |

---

## 1. Current logging implementation (WooCommerce Checkout plugin)

### 1.1 Primary mechanism: `add_log_message()`

Location: `snap-finance-functions.php`

```php
function add_log_message( $message = '' ) {
    $path = plugin_dir_path( __FILE__ ) . 'log.txt';
    // append plain text with timestamp to log.txt
    file_put_contents( $path, $old_message );
}
```

| Attribute | Current state |
| --- | --- |
| Format | Unstructured plain text, appended to `log.txt` in plugin root |
| Rotation | None — file grows unbounded |
| Levels | None (no INFO/WARN/ERROR distinction) |
| Structure | No JSON; not machine-parseable at scale |
| Git | `log.txt` is `.gitignore`d (correct); was previously tracked in some clones |
| WordPress integration | Does not use `WC_Logger` or `WP_DEBUG_LOG` |

### 1.2 What gets logged today

| Source | Events | Risk notes |
| --- | --- | --- |
| `get_snap_finance_token()` | JWT start/expiry/remaining on **every token check**; "Create new snap finance token" | High volume; token metadata in logs |
| `Snap_Finance_Address_Validator::log_failures()` | Address validation failures with country/state codes | Low PII (country/state only); useful for trends |
| `snap-finance-wc-order.php` | Order complete/cancel API responses via `print_r($response, true)` | May include API error bodies; order IDs and application IDs |
| Admin AJAX / order flows | Missing token, invalid order, API error messages | Operational; includes order # |

### 1.3 Frontend logging (not server-side)

Several JS files use `console.log()` (`snap-finance-application.js`, `snap-finance-state-field.js`, block checkout). These are **browser-only** and are **not** candidates for Sumo unless RUM is added separately.

### 1.4 Gaps vs Product requirements

- No centralized visibility — logs stay on each merchant server in `log.txt`
- No error taxonomy — cannot trend by `error_code` or integration step
- No opt-in / consent model for outbound telemetry
- Sensitive data risk — `print_r` of HTTP responses and verbose token logging
- Performance — synchronous `file_get_contents` + `file_put_contents` on entire file each write

---

## 2. Mechanisms evaluated for Sumo Logic forwarding

### Option A — Sumo Hosted Collector on merchant server

Install Sumo Logic Collector agent; tail `log.txt` or Apache/PHP logs.

| Pros | Cons |
| --- | --- |
| No plugin code for transport | Merchants must install/configure agent |
| Full log fidelity locally | Snap cannot mandate this across thousands of stores |
| | Collector credentials on merchant infrastructure |
| | Support and compliance burden on merchants |

**Verdict:** Not viable as Snap Product strategy.

### Option B — Plugin POSTs directly to Sumo HTTP Source

Each site configured with a Sumo HTTP Logs Source URL (or shared URL + `X-Sumo-Fields`).

| Pros | Cons |
| --- | --- |
| No collector | HTTP Source URL/token exposed in wp_options or wp-config |
| Sumo docs support gzip batch POST | **Synchronous outbound HTTP on checkout/admin paths** |
| | 30s timeout; 100KB–1MB payload guidance |
| | Per-merchant `_sourceCategory` chaos |
| | Hard to redact consistently across plugin versions |

**Verdict:** Avoid for runtime logging; acceptable only for a **Snap-internal staging** proof-of-concept.

### Option C — WordPress / WooCommerce native logger + merchant SIEM

Use `wc_get_logger()->log( $level, $message, array( 'source' => 'snap-finance' ) )` writing to `wp-content/uploads/wc-logs/`.

| Pros | Cons |
| --- | --- |
| WooCommerce-standard | Still local to merchant unless they forward WC logs |
| Respects WC log retention settings | Does not satisfy Snap Product centralized trends by itself |

**Verdict:** Adopt as **local logging layer**; combine with Option D for Snap telemetry.

### Option D — Snap-operated ingest relay → Sumo (recommended)

```
┌─────────────────────┐     async batch      ┌──────────────────────┐     HTTPS      ┌─────────────┐
│ WooCommerce Plugin  │ ──────────────────▶  │ Snap Ingest Relay    │ ────────────▶  │ Sumo Logic  │
│ (opt-in, redacted)  │   (WP Cron / AS)     │ (API Gateway/Lambda) │   HTTP Source  │  US2        │
└─────────────────────┘                      └──────────────────────┘                └─────────────┘
```

| Pros | Cons |
| --- | --- |
| No Sumo secrets on merchant sites | Requires new Snap backend service |
| Batching — minimal checkout impact | Initial engineering investment |
| Central redaction + schema enforcement | Opt-in adoption curve |
| Consistent `_sourceCategory` and fields | |
| Can disable relay without plugin update | |

**Verdict:** **Recommended production approach.**

---

## 3. Recommended approach (detailed)

### Phase 0 — Harden existing logging (prerequisite)

Before any Sumo forwarding, fix the local logger:

1. **Replace append-whole-file pattern** with locked append or `WC_Logger` backend.
2. **Introduce log levels** — `debug`, `info`, `warning`, `error`.
3. **Stop logging on every token refresh check** — log only failures and token *creation* at `info`.
4. **Remove `print_r( $response, true )`** — log structured fields: HTTP status, Snap error code, order id hash, application id prefix.
5. **Add log rotation** — max file size or WC log retention (7–30 days).

### Phase 1 — Structured Snap telemetry events (plugin)

Add `Snap_Finance_Logger` (new class under `includes/`):

```json
{
  "timestamp": "2026-09-01T12:00:00Z",
  "level": "error",
  "event": "snap.checkout.order_complete_failed",
  "plugin": "snap-finance-checkout",
  "plugin_version": "3.11.0",
  "wp_version": "6.9.0",
  "wc_version": "9.8.0",
  "php_version": "8.2.0",
  "snap_mode": "live",
  "context": "order_pay",
  "error_code": "shipping_amount_invalid",
  "http_status": 400,
  "store_id": "sha256:abc123…",
  "order_id_hash": "sha256:…",
  "application_id_prefix": "APP-12***"
}
```

**Never include:** client secrets, access tokens, JWT payloads, full customer name/email/address, full API response bodies, credit card data.

**Store identifier:** One-way hash of `site_url` + Snap partner client id (not raw URL) for grouping trends without exposing merchant domain in clear text unless merchant opts in to share domain.

### Phase 2 — Opt-in admin setting

WooCommerce → Settings → Payments → Snap Finance:

| Setting | Default | Purpose |
| --- | --- | --- |
| **Share anonymous error telemetry with Snap Finance** | Off | GDPR/consent; required before relay upload |
| Privacy link | — | Link to Snap privacy policy section |

Telemetry **off** = local logs only (Phase 0). Telemetry **on** = queue events for relay.

### Phase 3 — Async batch upload (plugin transport)

- Queue events in `wp_options` ( capped list ) or custom table `{prefix}snap_finance_telemetry_queue`.
- Flush via **Action Scheduler** (preferred if WooCommerce present) or `wp_cron` every 5–15 minutes.
- POST gzip JSON array to Snap relay:

  `POST https://telemetry.snapfinance.com/v1/woocommerce/events`  
  Headers: `Content-Type: application/json`, `Content-Encoding: gzip`, `X-Snap-Plugin: checkout`, `X-Snap-Plugin-Version: 3.11.0`

- **Circuit breaker:** After N consecutive failures, pause uploads 24h to protect merchant server and Snap infra.
- **Batch size:** 50–100 events or 64KB, whichever is smaller (Sumo HTTP guidance).
- **Timeout:** 5s max; non-blocking; never run on `checkout` or `order-pay` page load.

### Phase 4 — Snap ingest relay → Sumo Logic

Snap-operated service responsibilities:

1. Authenticate ingest (API key per plugin family or signed payload; **not** Sumo URL).
2. Validate schema; drop malformed events.
3. Enforce rate limits per `store_id` hash.
4. Forward to Sumo **HTTP Logs Source** with fixed metadata:

| Sumo field | Value |
| --- | --- |
| `_sourceCategory` | `prod/merchants/woocommerce/checkout` (and `sandbox/…`, `qa/…` by env) |
| `_sourceName` | `snap-woocommerce-checkout` |
| `_sourceHost` | `store_id` hash |
| `_source` | `snap-telemetry-relay` |

5. Optional: forward high-severity events to Cloud SIEM (checkbox on HTTP Source).

### Phase 5 — Sumo dashboards & monitors (Product)

Mirror existing Merchants ART Java observability patterns (`merchant-art-agents/skills/observability/*`):

| Dashboard panel | Query intent |
| --- | --- |
| Error volume by `event` | Top recurring integration failures |
| Error rate trend | `error` level / total events over 24h |
| Errors by `error_code` | e.g. `shipping_amount_invalid`, `address_validation_failed`, `token_missing` |
| Errors by `plugin_version` | Detect regressions after release |
| Errors by `snap_mode` | Sandbox vs live noise separation |
| New stores with errors | Unique `store_id` count per error type |

**Sample Log Search (US2):**

```sql
_sourceCategory=prod/merchants/woocommerce/checkout
| json auto
| where level = "error"
| count by event, error_code
| sort by _count desc
```

**Monitor example:** Alert when `shipping_amount_invalid` count > 10 in 1 hour across ≥ 3 distinct `store_id` values (indicates systemic issue, not one merchant misconfiguration).

---

## 4. Security considerations

| Risk | Mitigation |
| --- | --- |
| Sumo HTTP URL/token theft from merchant DB | Never store Sumo credentials on merchant sites; use Snap relay |
| Client secret / token exfiltration via logs | Redact in logger; ban `print_r` on API responses; static analysis in code review |
| PII in centralized logs | Allowlist fields only; hash identifiers; no raw addresses/emails |
| MITM on telemetry POST | TLS 1.2+ only; certificate pinning optional in future |
| Replay / spam | Rate limit at relay; API key rotation; store_id throttling |
| Merchant without consent | Default opt-in **off**; clear admin disclosure |

---

## 5. Performance considerations

| Concern | Mitigation |
| --- | --- |
| Synchronous file I/O on checkout | Move to WC_Logger async handler or queue-only for telemetry |
| Outbound HTTP during payment | **Never** on checkout request path; cron/Action Scheduler only |
| Large log files | Rotation + telemetry queue cap (e.g. 500 events) |
| Token check logs every page load | Reduce to error-only + explicit token refresh events |
| Sumo 30s HTTP timeout | Keep batches < 1MB gzip; 5s client timeout with retry backoff |

---

## 6. Privacy considerations

| Topic | Approach |
| --- | --- |
| GDPR / CCPA | Opt-in telemetry; data minimization; retention policy in relay (e.g. 90 days in Sumo) |
| Merchant identification | Hashed `store_id`; optional domain sharing only with explicit consent |
| Customer identification | No customer PII in telemetry; hash order id if needed for deduplication |
| Right to erasure | Telemetry uses hashed ids — no direct customer mapping stored in Snap |
| Data residency | Confirm Sumo US2 storage aligns with Snap legal review for merchant analytics |

---

## 7. Implementation roadmap

| Phase | Deliverable | Owner | Effort |
| --- | --- | --- | --- |
| 0 | Harden `add_log_message` / migrate to `Snap_Finance_Logger` | Plugin team | 1–2 sprints |
| 1 | Structured events + unit tests | Plugin team | 1 sprint |
| 2 | Admin opt-in setting + privacy copy | Plugin + Legal | 0.5 sprint |
| 3 | Async queue + relay client in plugin | Plugin team | 1 sprint |
| 4 | Snap ingest relay service + Sumo HTTP Source | Platform / DevOps | 2 sprints |
| 5 | Sumo dashboards + monitors | Product / SRE | 1 sprint (after data flowing) |

**Marketing plugin:** Apply the same `Snap_Finance_Logger` + telemetry contract in `woocommerce-marketing-plugin` (or equivalent) with `_sourceCategory=prod/merchants/woocommerce/marketing`.

---

## 8. Alternatives for enterprise merchants (out of scope for Product telemetry)

Merchants with existing Splunk/Datadog/Sumo contracts may prefer to forward `wp-content/uploads/wc-logs/snap-finance-*.log` themselves. Document WC_Logger file locations in plugin README; do not embed merchant Sumo URLs in plugin settings.

---

## 9. Acceptance criteria mapping

| Acceptance criterion | How this document satisfies it |
| --- | --- |
| A recommended approach for sending WooCommerce plugin logs to Sumo Logic is documented | **Section 3 (Option D)** — Snap-operated ingest relay with opt-in batched redacted events, plus Sumo `_sourceCategory` and dashboard guidance |

---

## 10. Immediate next steps

1. **Product/Legal:** Approve opt-in telemetry model and retention period.
2. **Plugin team:** Phase 0 hardening PR — remove verbose token logging and `print_r` responses.
3. **Platform team:** Spike Snap ingest relay (API Gateway + Lambda → Sumo HTTP Source US2).
4. **SRE:** Create `_sourceCategory=prod/merchants/woocommerce/checkout` and baseline error dashboard once staging events flow.

---

*Document version: 1.0 — September 2026*
