Skip to main content

Overview

The Logger class provides a lightweight file-based logging system for the WhatsApp RAG Bot. It supports multiple log levels and automatically organizes logs by date in the logs/ directory.
Logs are stored as plain text files with one entry per line, making them easy to parse and analyze with standard Unix tools like grep, tail, and awk.

Initialization

use App\Core\Logger;

// Initialize with default path (logs/ directory)
$logger = new Logger();

// Or specify a custom log directory
$logger = new Logger('/var/log/whatsapp-bot');
The Logger automatically creates the log directory if it doesn’t exist with 0755 permissions.

Log Levels

The Logger supports four standard log levels:
LevelMethodUse Case
INFOinfo()General application events, successful operations
WARNINGwarning()Warning conditions, non-critical issues
ERRORerror()Error conditions, failed operations
DEBUGdebug()Detailed debugging information

Basic Logging

use App\Core\Logger;

$logger = new Logger();

// Log successful operations
$logger->info('WhatsApp message sent successfully');
$logger->info('Document uploaded and processed');
$logger->info('User conversation started', ['phone' => '+1234567890']);

Contextual Logging

Add structured context to log entries for better debugging:
use App\Core\Logger;

$logger = new Logger();

// Log with context array
$logger->info('Message received', [
    'from' => '+1234567890',
    'message_id' => 'wamid.HBgLM...',
    'type' => 'text',
    'timestamp' => time()
]);

// Context is JSON-encoded
$logger->error('API request failed', [
    'endpoint' => 'https://graph.facebook.com/v17.0/messages',
    'status' => 401,
    'response' => 'Invalid access token'
]);

Log File Structure

File Organization

Logs are stored in daily files with the format YYYY-MM-DD.log:
logs/
├── 2026-03-04.log
├── 2026-03-05.log
└── 2026-03-06.log

Log Entry Format

Each log entry follows this format:
[YYYY-MM-DD HH:MM:SS] [LEVEL] Message {"context":"json"}
Example log file (logs/2026-03-06.log):
[2026-03-06 10:15:23] [INFO] WhatsApp webhook received {"type":"message","phone":"+1234567890"}
[2026-03-06 10:15:24] [INFO] Processing text message {"length":42,"conversation_id":156}
[2026-03-06 10:15:25] [DEBUG] RAG search initiated {"query":"product pricing","chunks":5}
[2026-03-06 10:15:26] [INFO] AI response generated {"confidence":0.87,"tokens":234}
[2026-03-06 10:15:27] [INFO] Message sent to user {"message_id":"wamid.HBgL..."}
[2026-03-06 10:20:15] [ERROR] OpenAI API error {"status_code":429,"error":"Rate limit exceeded"}
[2026-03-06 10:20:16] [WARNING] Falling back to cached response

Real-World Examples

use App\Core\Logger;
use App\Services\WhatsAppService;

$logger = new Logger();

try {
    $logger->info('Webhook received', [
        'from' => $phoneNumber,
        'type' => $messageType
    ]);
    
    // Process message
    $response = $whatsapp->sendMessage($phoneNumber, $reply);
    
    $logger->info('Message sent successfully', [
        'to' => $phoneNumber,
        'message_id' => $response['messages'][0]['id']
    ]);
    
} catch (Exception $e) {
    $logger->error('Failed to send message', [
        'error' => $e->getMessage(),
        'phone' => $phoneNumber
    ]);
}

Log Analysis

Use standard Unix tools to analyze logs:
# View last 50 log entries
tail -n 50 logs/2026-03-06.log

# Follow logs in real-time
tail -f logs/2026-03-06.log

API Reference

__construct(string $logPath = null)

Initializes the logger with a log directory path. Location: src/Core/Logger.php:9 Parameters:
  • $logPath (string, optional): Path to log directory. Defaults to logs/ in project root.
Behavior: Creates directory if it doesn’t exist with 0755 permissions

log(string $message, string $level = 'INFO', array $context = [])

Writes a log entry with the specified level and context. Location: src/Core/Logger.php:18 Parameters:
  • $message (string): Log message
  • $level (string): Log level (INFO, WARNING, ERROR, DEBUG)
  • $context (array): Optional context data (JSON-encoded)

info(string $message, array $context = [])

Logs an informational message. Location: src/Core/Logger.php:35 Parameters:
  • $message (string): Log message
  • $context (array): Optional context data

error(string $message, array $context = [])

Logs an error message. Location: src/Core/Logger.php:40 Parameters:
  • $message (string): Error description
  • $context (array): Optional error details

debug(string $message, array $context = [])

Logs a debug message. Location: src/Core/Logger.php:45 Parameters:
  • $message (string): Debug information
  • $context (array): Optional debug data

warning(string $message, array $context = [])

Logs a warning message. Location: src/Core/Logger.php:50 Parameters:
  • $message (string): Warning description
  • $context (array): Optional warning details

Best Practices

Use Appropriate Levels

Use INFO for normal operations, WARNING for potential issues, ERROR for failures, and DEBUG for development.

Add Context

Always include relevant context (IDs, timestamps, values) to make debugging easier.

Log Rotation

Implement log rotation to prevent disk space issues. Consider using logrotate on Linux.

Sensitive Data

Never log sensitive data like passwords, API keys, or full credit card numbers.

Log Rotation

On Linux systems, use logrotate to manage log files:
/etc/logrotate.d/whatsapp-bot
/path/to/whatsapp-rag-bot/logs/*.log {
    daily
    rotate 30
    compress
    delaycompress
    missingok
    notifempty
    create 0644 www-data www-data
}

Database

Log database operations and errors

Error Handling

Exception handling and error recovery

Build docs developers (and LLMs) love