# Laravel Log Viewer - Documentation

## 📋 Overview

Laravel Log Viewer is now integrated into the application, providing a web-based UI for viewing and managing Laravel logs.

## 🔐 Access Control

**Who Can Access:**
- Super Admins (`role = 'super_admin'`)
- Admins (`role = 'admin'`)

**URL:** `/admin/logs`

## ✨ Features

- 📊 **View all log files** in `storage/logs/`
- 🔍 **Search & filter** log entries
- 📅 **Sort by date, level** (emergency, alert, critical, error, warning, notice, info, debug)
- 📥 **Download log files** individually
- 🗑️ **Delete log files** (with confirmation)
- 🎨 **Clean, responsive UI**

## 🎯 How to Use

### Access via Admin Menu

1. Login as admin/super admin
2. Click **Logs** in the sidebar menu (between Ujian and Pengaturan)
3. You'll see a list of all log files

### View Logs

1. Click on any log file to view its contents
2. Logs are displayed with:
   - **Color coding** by severity level
   - **Stack traces** for errors
   - **Timestamp** for each entry
   - **Context** information

### Filter & Search

- **Filter by level**: Click on severity icons (ERROR, WARNING, INFO, etc.)
- **Search**: Use the search box to find specific text
- **Date range**: Filter logs by date

### Download Logs

1. Open a log file
2. Click the **Download** button
3. File will be downloaded as `.log`

### Delete Logs

1. Click the **Delete** icon next to a log file
2. Confirm deletion
3. **⚠️ Warning:** This action cannot be undone!

## 🔧 Configuration

Config file: `config/log-viewer.php`

### Key Settings:

```php
'route' => env('LOG_VIEWER_ROUTE_PATH', 'logs'),
'middleware' => ['web', 'auth', 'can:view logs'],
'pattern' => '*.log',
'depth' => 10,
```

### Customize Settings:

**Change route path:**
```env
# In .env
LOG_VIEWER_ROUTE_PATH=admin-logs
```

**Hide specific files:**
```php
// In config/log-viewer.php
'hide_files' => [
    '.gitignore',
    '.DS_Store',
    'laravel.log', // Hide main log if needed
],
```

## 📁 Log Files Location

All log files are stored in:
```
storage/logs/
├── laravel.log
├── laravel-2024-03-30.log
└── ...
```

## 🛡️ Security

### Permission Gates

Two gates are defined in `app/Providers/AppServiceProvider.php`:

1. **`access admin`** - Checks if user is admin or super_admin
2. **`view logs`** - Checks if user can view logs (same as above)

### Protected Routes

- ✅ All routes require authentication
- ✅ Only admins can access logs
- ✅ `@can('view logs')` directive used in views

## 🚨 Log Levels

From most severe to least:

1. **EMERGENCY** (🔴) - System is unusable
2. **ALERT** (🟠) - Immediate action required
3. **CRITICAL** (🟠) - Critical conditions
4. **ERROR** (🟡) - Error conditions
5. **WARNING** (🟡) - Warning conditions
6. **NOTICE** (🟢) - Normal but significant
7. **INFO** (🔵) - Informational messages
8. **DEBUG** (⚪) - Debug-level messages

## 📝 Common Use Cases

### 1. Debug Production Issues

```php
// In your code
\Log::error('User failed to login', ['user_id' => $user->id]);
\Log::warning('Payment gateway slow', ['response_time' => $ms]);
\Log::info('Exam submitted', ['exam_id' => $exam->id, 'score' => $score]);
```

Then view in `/admin/logs`

### 2. Monitor Cheating Logs

Anti-cheating logs are stored with context:
- Type: `tab_switch`, `blur`, `devtools`
- User ID, Exam Session ID
- IP Address, User Agent
- Timestamp

### 3. Track API Errors

API errors are automatically logged with stack traces

## 🔍 Troubleshooting

### "403 Forbidden" when accessing logs

**Issue:** You don't have permission to view logs

**Solution:**
- Ensure your user role is `super_admin` or `admin`
- Check `AppServiceProvider.php` gate definitions
- Clear cache: `php artisan config:clear`

### "No log files found"

**Issue:** No logs exist in `storage/logs/`

**Solution:**
- Logs are created when errors occur
- Check `.env` `LOG_CHANNEL` setting
- Ensure `storage/logs` is writable

### Logs not displaying

**Issue:** Blank page or error when viewing logs

**Solution:**
```bash
php artisan cache:clear
php artisan view:clear
chmod -R 755 storage/logs
```

## 📊 Log Retention

### Best Practices:

1. **Regular cleanup** - Don't let logs grow too large
2. **Archive old logs** - Move old logs to backup
3. **Monitor disk space** - Logs can fill up storage
4. **Set log levels** - Use DEBUG in dev, INFO/WARNING in prod

### Cleanup Command

```bash
# Delete logs older than 30 days
find storage/logs/*.log -mtime +30 -delete

# Or compress old logs
find storage/logs/*.log -mtime +7 -gzip
```

## 🔗 Integration with Existing Features

### Anti-Cheating Logs

Cheating detection events are logged:

```php
// In CheatingDetectionController
Log::warning('Cheating event detected', [
    'user_id' => $user->id,
    'exam_session_id' => $request->input('exam_session_id'),
    'type' => $request->input('type'),
    'ip_address' => $request->ip(),
]);
```

View these in `/admin/logs` and search for "Cheating"

### Exam Errors

Exam-related errors are automatically logged:
- Database query failures
- File upload errors
- Validation errors

## 📚 Additional Resources

- **Package Docs:** https://github.com/rap2hpoutre/laravel-log-viewer
- **Laravel Logging:** https://laravel.com/docs/logging
- **Log Levels:** https://www.php.net/manual/en/function.syslog.php

## 🎯 Quick Access

- **Admin Menu:** Logs icon in sidebar
- **Direct URL:** `https://yourdomain.com/admin/logs`
- **Keyboard Shortcuts:** Use browser search (Ctrl+F) to find specific logs

---

**Last Updated:** 2026-03-30
**Version:** 2.5.0
