# Browser Log Capture Procedure

**Purpose**: Hook to automatically capture and retrieve all browser-side logs from DSS dashboard

---

## Quick Access Commands

When the dashboard is loaded in a browser, open DevTools Console and run:

```javascript
// Get all logs
window.__DSS_BROWSER_LOGS.all()

// Get errors only
window.__DSS_BROWSER_LOGS.errors()

// Get network requests
window.__DSS_BROWSER_LOGS.network()

// Get system diagnostic
window.__DSS_BROWSER_LOGS.diagnostic()

// Export everything as JSON
window.__DSS_BROWSER_LOGS.export()

// Print formatted to console
window.__DSS_BROWSER_LOGS.print()

// Clear logs
window.__DSS_BROWSER_LOGS.clear()
```

---

## Automated Procedure (The Hook)

### Step 1: Browser Logger is Auto-Loaded

The `browser-logger.js` module is automatically initialized when the dashboard loads. It captures:

- ✅ All console.log/warn/error/info/debug calls
- ✅ Uncaught errors and promise rejections
- ✅ Network requests (fetch API)
- ✅ Performance metrics (page load, long tasks)
- ✅ Memory usage warnings
- ✅ Full stack traces

### Step 2: Access Logs Programmatically

**From Browser Console**:
```javascript
// Get diagnostic summary
const diagnostic = window.__DSS_BROWSER_LOGS.diagnostic();
console.table(diagnostic);

// Get last 50 errors
const errors = window.__DSS_BROWSER_LOGS.errors();
console.table(errors);

// Search logs
const rawLogger = window.__DSS_BROWSER_LOGGER;
const searchResults = rawLogger.getLogs({
  search: 'config',
  limit: 20
});
```

**Export to File**:
```javascript
// Export all logs as JSON
const data = window.__DSS_BROWSER_LOGS.export();
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `dss-browser-logs-${Date.now()}.json`;
a.click();
```

### Step 3: API Endpoint for Remote Retrieval

**TODO**: Create `/api/browser-logs` endpoint that allows server to request logs from connected clients.

This would enable:
```bash
curl http://localhost:3456/api/browser-logs
```

---

## What Gets Captured

### Console Output
```javascript
{
  timestamp: 1733456789000,
  level: 'log|warn|error|info|debug',
  category: 'console',
  message: 'Application initialized successfully',
  data: { args: [...] }
}
```

### Errors
```javascript
{
  timestamp: 1733456789000,
  level: 'error',
  category: 'uncaughtError|unhandledRejection',
  message: 'Cannot read property of undefined',
  data: {
    filename: '/admin-ui/js/core/app.js',
    lineno: 42,
    colno: 15,
    stack: '...'
  }
}
```

### Network Requests
```javascript
{
  timestamp: 1733456789000,
  level: 'network',
  category: 'fetch',
  message: 'GET /api/config',
  data: {
    method: 'GET',
    url: '/api/config',
    status: 200,
    statusText: 'OK',
    duration: 45,
    headers: { 'content-type': 'application/json' }
  }
}
```

### Performance Metrics
```javascript
{
  timestamp: 1733456789000,
  level: 'metric',
  category: 'performance',
  message: 'Page load completed',
  data: {
    domContentLoaded: 250,
    loadComplete: 450,
    totalTime: 1200,
    dnsLookup: 5,
    tcpConnection: 10,
    requestTime: 20,
    responseTime: 100,
    renderTime: 800
  }
}
```

---

## Integration Points

### 1. Add to HTML (Required)

**File**: `/admin-ui/index.html`

Add before other scripts:
```html
<script type="module">
  import browserLogger from '/admin-ui/js/core/browser-logger.js';
  console.log('[BrowserLogger] Initialized');
</script>
```

Or add to app.js imports:
```javascript
import browserLogger from './core/browser-logger.js';
```

### 2. API Endpoint (Optional)

**File**: `/tools/api/server.py`

Add endpoint to retrieve logs from sessionStorage:
```python
@app.get("/api/browser-logs")
async def get_browser_logs(session_id: str = None):
    """
    Endpoint to request browser logs from clients.

    The client must POST their logs here, as server
    cannot directly access browser sessionStorage.
    """
    # Implementation would store logs sent by client
    pass

@app.post("/api/browser-logs")
async def receive_browser_logs(logs: dict):
    """Receive and store browser logs from client"""
    # Store logs in database or file
    pass
```

### 3. Auto-Upload on Error

**File**: `/admin-ui/js/core/browser-logger.js`

Add automatic upload when critical error occurs:
```javascript
captureErrors() {
  window.addEventListener('error', (event) => {
    this.log('error', 'uncaughtError', event.message, {...});

    // Auto-upload on critical errors
    if (this.isCriticalError(event)) {
      this.uploadToServer();
    }
  });
}

async uploadToServer() {
  const logs = this.exportJSON();
  await fetch('/api/browser-logs', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(logs)
  });
}
```

---

## Usage Scenarios

### Scenario 1: User Reports Dashboard Not Loading
```javascript
// In browser console
window.__DSS_BROWSER_LOGS.diagnostic()
// Check: errorCount, recent errors, network failures
```

### Scenario 2: Performance Issues
```javascript
window.__DSS_BROWSER_LOGS.network()
// Check: slow requests, failed requests
// Look for requests >1000ms duration
```

### Scenario 3: Debugging Configuration Issues
```javascript
const rawLogger = window.__DSS_BROWSER_LOGGER;
rawLogger.getLogs({
  search: 'config',
  level: 'error',
  limit: 50
})
// Find config-related errors
```

### Scenario 4: Export for Offline Analysis
```javascript
// Export and download
const data = window.__DSS_BROWSER_LOGS.export();
// Save to file or send to developer
```

---

## Memory & Performance

### Storage Limits
- **Max entries**: 1000 (configurable)
- **Storage**: sessionStorage (survives page reload, cleared on tab close)
- **Memory**: ~1-5MB typical, auto-truncates oldest entries

### Performance Impact
- **Console overhead**: Minimal (<1ms per log)
- **Network overhead**: Minimal (intercepts, doesn't duplicate)
- **Memory overhead**: ~1-2MB average

### When to Clear
```javascript
// Clear logs to free memory
window.__DSS_BROWSER_LOGS.clear()
```

---

## Troubleshooting

### Logger Not Found
```javascript
// Check if loaded
if (window.__DSS_BROWSER_LOGGER) {
  console.log('✅ Logger loaded');
} else {
  console.log('❌ Logger not loaded - check browser-logger.js import');
}
```

### Logs Not Persisting
- sessionStorage might be disabled
- Private/Incognito mode may have restrictions
- Check browser console for storage errors

### No Network Logs
- Logger must be loaded BEFORE other modules
- Check import order in HTML/app.js

---

## Next Steps

1. ✅ Created browser-logger.js (done)
2. ⏳ Add import to index.html or app.js
3. ⏳ Test in browser DevTools
4. ⏳ Create API endpoint for remote retrieval
5. ⏳ Add auto-upload on critical errors
6. ⏳ Integrate with existing debug-inspector.js

---

## Related Documentation

- `.dss/DSS_SELF_DEBUG_METHODOLOGY.md` - Self-debugging procedures
- `.dss/DEBUG_QUICKSTART.md` - Quick debugging guide
- `admin-ui/js/core/debug-inspector.js` - Server-side debug tools
- `admin-ui/js/core/audit-logger.js` - Audit trail logging
