What are the benefits of implementing a custom Logger class in PHP projects?
Implementing a custom Logger class in PHP projects allows for better control and customization of logging functionality. It enables developers to log specific information, format log messages, and define log levels according to the project's requirements. This can help in debugging, monitoring, and tracking the application's behavior, making it easier to identify and fix issues.
<?php
class Logger {
public function log($message, $level = 'info') {
$formattedMessage = '[' . strtoupper($level) . '] ' . date('Y-m-d H:i:s') . ': ' . $message . PHP_EOL;
file_put_contents('log.txt', $formattedMessage, FILE_APPEND);
}
}
// Example usage
$logger = new Logger();
$logger->log('This is an info message');
$logger->log('This is an error message', 'error');
?>