# Log Rotation Runbook

This document covers host-level log rotation for TheSol Chat production deployments.
The application itself caps individual log files via `SB_LOG_MAX_BYTES` (configurable in `config.php`), but host-level rotation is still required for the PHP error log, web server access/error logs, and any external log files written by the queue worker or maintenance cron.

---

## 1. Application-Level Log Cap

`config.php` defines `SB_LOG_MAX_BYTES` (default 5 MB). The `sb_log()` helper truncates the log file once this limit is exceeded. This provides a hard safety net, but does **not** keep historical log archives — for auditing you need host-level rotation.

```php
// config.php — adjust as needed
define('SB_LOG_MAX_BYTES', 5 * 1024 * 1024); // 5 MB
```

---

## 2. Linux — logrotate

Create `/etc/logrotate.d/thesol-chat`:

```
/var/log/thesol-chat/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 www-data www-data
    sharedscripts
    postrotate
        # Reload PHP-FPM so it re-opens the error log (adjust pool name as needed)
        systemctl reload php8.2-fpm 2>/dev/null || true
    endscript
}
```

Also rotate the PHP error log if it's written outside the app log directory:

```
/var/log/php8.2-fpm.log {
    weekly
    rotate 8
    compress
    missingok
    notifempty
    create 0640 root adm
}
```

Test the config:

```bash
sudo logrotate --debug /etc/logrotate.d/thesol-chat
```

Force immediate rotation:

```bash
sudo logrotate --force /etc/logrotate.d/thesol-chat
```

---

## 3. Apache on Linux (non-cPanel)

Apache's built-in `rotatelogs` utility can be used in `httpd.conf` or the VirtualHost block:

```apache
ErrorLog  "|/usr/bin/rotatelogs /var/log/thesol-chat/apache-error.%Y-%m-%d.log 86400"
CustomLog "|/usr/bin/rotatelogs /var/log/thesol-chat/apache-access.%Y-%m-%d.log 86400" combined
```

Alternatively rely on the system logrotate config and send `SIGUSR1` to Apache in the `postrotate` hook:

```
postrotate
    /bin/kill -USR1 $(cat /var/run/apache2/apache2.pid 2>/dev/null) 2>/dev/null || true
endscript
```

---

## 4. cPanel Hosting

cPanel rotates Apache logs automatically (usually weekly). The `error_log` path for PHP is typically inside `~/logs/` or `/usr/local/cpanel/logs/`. Check **cPanel → Error Log** for the active path.

For the application log and queue worker log, add a daily cPanel cron:

```
# cPanel cron — rotate app logs older than 14 days
0 3 * * * find /home/USERNAME/logs/thesol-chat/ -name "*.log" -mtime +14 -delete
```

---

## 5. Windows (XAMPP / IIS)

PHP on Windows writes to the path in `php.ini > error_log`. The application also writes to `SB_LOG_PATH`.

### Option A — PowerShell scheduled task (daily at 03:00)

```powershell
# rotate-logs.ps1
$logDir = "C:\xampp\htdocs\Chatbot\logs"
$maxAgeDays = 14
Get-ChildItem -Path $logDir -Filter "*.log" -File |
    Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$maxAgeDays) } |
    Remove-Item -Force
```

Register as a scheduled task:

```powershell
$action  = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-NonInteractive -File C:\scripts\rotate-logs.ps1"
$trigger = New-ScheduledTaskTrigger -Daily -At "03:00"
Register-ScheduledTask -TaskName "ThesolChatLogRotation" -Action $action -Trigger $trigger -RunLevel Highest
```

### Option B — Windows Event Log integration

Set `error_log = syslog` in `php.ini` to write PHP errors to the Windows Application event log. Windows event logs are automatically managed (circular buffer, default 20 MB).

---

## 6. Queue Worker and Maintenance Cron Logs

The queue worker and maintenance script redirect their output to log files. Add log rotation for these:

**Linux logrotate addition** (append to the config in section 2):

```
/var/log/thesol-chat/queue-worker.log
/var/log/thesol-chat/queue-cleanup.log
/var/log/thesol-chat/maintenance.log {
    weekly
    rotate 8
    compress
    missingok
    notifempty
    create 0640 www-data www-data
}
```

**cPanel / shared hosting** — use a cron to truncate logs that exceed a size threshold:

```bash
# Truncate queue worker log if > 50 MB
find ~/logs/thesol-chat/ -name "queue-worker.log" -size +50M -exec truncate -s 0 {} \;
```

---

## 7. Verification Checklist

| Check | Command |
|---|---|
| logrotate config syntax | `logrotate --debug /etc/logrotate.d/thesol-chat` |
| Confirm rotation works | `logrotate --force /etc/logrotate.d/thesol-chat` |
| Check compressed archives | `ls -lh /var/log/thesol-chat/` |
| PHP error log not growing unboundedly | `ls -lh $(php -r 'echo ini_get("error_log");')` |
| Application log size | `ls -lh logs/*.log` |

---

## 8. Recommended Defaults Summary

| Log source | Rotation trigger | Keep |
|---|---|---|
| PHP error log (`error_log`) | Daily or 50 MB | 14 days |
| Apache error/access log | Daily | 14 days |
| Queue worker log | Weekly | 8 weeks |
| Maintenance log | Weekly | 8 weeks |
| App log (`SB_LOG_PATH`) | App-level cap `SB_LOG_MAX_BYTES` | In-place (no archive) |
