How can the Logger class be extended to handle additional functionalities such as sending email notifications to administrators?
To extend the Logger class to handle sending email notifications to administrators, you can create a new method within the Logger class that sends an email when a critical error is logged. This method can utilize PHP's built-in mail function to send an email to the specified administrators. Additionally, you can add parameters to the Logger class constructor to specify the email recipients and other email details.
class Logger {
private $logFile;
public function __construct($logFile) {
$this->logFile = $logFile;
}
public function log($message) {
// Log message to file
file_put_contents($this->logFile, $message . PHP_EOL, FILE_APPEND);
// Check if message is critical and send email notification
if (strpos($message, 'CRITICAL') !== false) {
$this->sendEmailNotification('admin@example.com', 'Critical Error', $message);
}
}
private function sendEmailNotification($to, $subject, $message) {
$headers = 'From: admin@example.com' . "\r\n";
mail($to, $subject, $message, $headers);
}
}
// Example usage
$logger = new Logger('error.log');
$logger->log('INFO: This is an informational message');
$logger->log('CRITICAL: This is a critical error that requires immediate attention');