<?php
/**
* Class Logger.
* A simple logger class for internal tooling.
*/
class Logger {
/**
* Log level. Can be 'debug', 'info', 'warning', 'error', 'critical'.
* @var string
*/
private string $level = 'info';
/**
* Log file path.
* @var string
*/
private string $filePath;
/**
* Logger constructor.
* @param string $filePath The path to the log file.
*/
public function __construct(string $filePath) {
$this->filePath = $filePath;
}
/**
* Logs a message to the log file.
* @param string $message The message to log.
* @param string $level The log level (debug, info, warning, error, critical).
* @return bool True on success, false on failure.
*/
public function log(string $message, string $level = 'info'): bool {
// Validate log level
$validLevels = ['debug', 'info', 'warning', 'error', 'critical'];
if (!in_array($level, $validLevels)) {
$level = 'info'; // Default to info if invalid
}
// Prepare the log entry
$timestamp = date('Y-m-d H:i:s');
$logEntry = "[$timestamp] [$level] $message\n";
// File open for appending
$fileHandle = fopen($this->filePath, 'a');
if ($fileHandle) {
// Write the log entry to the file
if (fwrite($fileHandle, $logEntry)) {
fclose($fileHandle);
return true; // Log successful
} else {
fclose($fileHandle);
return false; // Log failed
}
} else {
return false; // Failed to open log file.
}
}
/**
* Logs a debug message.
* @param string $message The debug message.
* @return bool True on success, false on failure.
*/
public function debug(string $message): bool {
return $this->log($message, 'debug');
}
/**
* Logs an informational message.
* @param string $message The informational message.
* @return bool True on success, false on failure.
*/
public function info(string $message): bool {
return $this->log($message, 'info');
}
/**
* Logs a warning message.
* @param string $message The warning message.
* @return bool True on success, false on failure.
*/
public function warning(string $message): bool {
return $this->log($message, 'warning');
}
/**
* Logs an error message.
* @param string $message The error message.
* @return bool True on success, false on failure.
*/
public function error(string $message): bool {
return $this->log($message, 'error');
}
/**
* Logs a critical message.
* @param string $message The critical message.
* @return bool True on success, false on failure.
*/
public function critical(string $message): bool {
return $this->log($message, 'critical');
}
}
?>
Add your comment