# Website Toolbox Forum - Logging System

## Overview
The logging system provides comprehensive tracking of SSO authentication, API requests, errors, and other critical operations. This feature helps administrators troubleshoot issues on client websites by providing detailed logs with filtering, searching, and export capabilities.

## Features

### 1. **Centralized Logging**
- **Four Log Levels:**
  - **Error**: Critical failures and errors
  - **Warning**: Warning messages and potential issues
  - **Info**: General informational messages
  - **Debug**: Detailed debugging information

- **Categories:**
  - `SSO`: Single Sign-On authentication events
  - `SSO_API`: SSO API requests and responses
  - `API`: Forum API requests
  - Custom categories can be added as needed

### 2. **Database Storage**
- Logs are stored in a dedicated database table (`wp_wtb_forum_logs`)
- Includes metadata: timestamp, level, category, message, context, user ID, user agent
- Automatic cleanup based on retention period

### 3. **Admin Interface**
Located at **Website Toolbox > Logs** in WordPress admin:

#### Viewing Logs
- Paginated table view with 50 logs per page
- Color-coded log levels for easy identification
- Expandable context information for detailed debugging
- Shows associated user and user agent

#### Filtering & Search
- **Filter by Log Level**: Error, Warning, Info, Debug
- **Filter by Category**: SSO, API, etc.
- **Search**: Full-text search across messages and context
- Filters can be combined for precise results

#### Actions
- **Download Logs**: Export filtered logs as text file
- **Clear All Logs**: Remove all log entries (with confirmation)
- Shows total log count

### 4. **Settings**
Located in **Website Toolbox > Settings** in the WordPress admin menu:

#### Enable Logging
- Toggle logging on/off
- Default: Enabled
- When disabled, no new logs are created

#### Log Retention Days
- Set how long logs are kept (1-365 days)
- Default: 30 days
- Old logs are automatically deleted

## Log Categories

### SSO (Single Sign-On)
Tracks WordPress-to-Forum authentication:
- Login attempts
- Success/failure status
- Forum address changes
- Cookie operations

### SSO_API
Tracks SSO API communications:
- Authentication token requests
- API responses
- Authentication failures
- Missing configuration warnings

### API
Tracks Forum REST API operations:
- GET/POST requests
- Response status codes
- Error responses
- Failed requests

## Usage Examples

### Viewing SSO Login Issues
1. Go to **Website Toolbox > Logs**
2. Filter by **Level: Error** and **Category: SSO**
3. Review failed authentication attempts
4. Click "Show Context" for detailed error information

### Exporting Logs for Support
1. Apply desired filters (e.g., last 24 hours, Error level)
2. Click **Download Logs**
3. Send the downloaded text file to support team

### Investigating User-Specific Issues
1. Search for the username or user ID
2. Review all log entries for that user
3. Check user agent and context for additional details

## Technical Details

### Logger Class
Location: `core/logger.php`

#### Usage in Code:
```php
use WebsiteToolboxLogger\Logger;

// Log levels
Logger::error('CATEGORY', 'Error message', $context_array);
Logger::warning('CATEGORY', 'Warning message', $context_array);
Logger::info('CATEGORY', 'Info message', $context_array);
Logger::debug('CATEGORY', 'Debug message', $context_array);
```

#### Context Array (Optional):
```php
$context = array(
    'user_id' => 123,
    'username' => 'john_doe',
    'url' => 'https://example.com/api',
    'error_code' => 500
);
```

### Database Schema
```sql
CREATE TABLE wp_wtb_forum_logs (
    id bigint(20) AUTO_INCREMENT PRIMARY KEY,
    log_time datetime DEFAULT CURRENT_TIMESTAMP,
    log_level varchar(20),
    category varchar(100),
    message text,
    context text,
    user_id bigint(20),
    user_agent varchar(255),
    KEY log_time (log_time),
    KEY log_level (log_level),
    KEY category (category)
);
```

### Automatic Cleanup
- Runs daily via WordPress cron job
- Deletes logs older than retention period
- Configurable via settings

## Best Practices

1. **Enable Logging During Troubleshooting**
   - Turn on logging when investigating issues
   - Review logs regularly
   - Disable if performance is a concern on high-traffic sites

2. **Set Appropriate Retention**
   - 7 days for high-traffic sites
   - 30 days (default) for normal sites
   - 90+ days for compliance requirements

3. **Use Filters Effectively**
   - Start with Error level to find critical issues
   - Use category filters to narrow down problems
   - Search for specific error messages or usernames

4. **Regular Maintenance**
   - Download important logs before clearing
   - Clear logs periodically to maintain performance
   - Review retention settings based on storage capacity

## Privacy & Security

- **User Agent**: Browser/client information is logged for debugging
- **User Information**: Only user ID and username (no passwords)
- **Sensitive Data**: Context may contain URLs and API responses. Sensitive fields matching patterns like 'password', 'authtoken', 'api_key', 'apikey', 'secret', 'token', 'auth', 'cookie', and 'session' are automatically redacted. However, sensitive data may still be logged if present in non-matching field names or embedded in URLs/strings.
- **Access Control**: Only administrators can view logs

## Performance Considerations

- Logging has minimal impact on site performance
- Database queries are optimized with indexes
- Automatic cleanup prevents table bloat
- Consider disabling Debug level on production sites

## Troubleshooting

### Logs Not Appearing
1. Check if logging is enabled in settings
2. Verify database table was created
3. Check PHP error logs for database errors

### Too Many Logs
1. Reduce retention period
2. Clear old logs manually
3. Consider disabling Debug level
4. Filter logging by category in code

### Performance Issues
1. Clear old logs
2. Reduce retention period
3. Add database indexes if needed
