60 lines
1.8 KiB
PHP
60 lines
1.8 KiB
PHP
<?php
|
|
|
|
|
|
namespace App\Core;
|
|
|
|
class Logger {
|
|
private string $logFile;
|
|
private int $maxSize = 5242880;
|
|
private int $maxFiles = 5;
|
|
|
|
public function __construct(string $filename = 'app.log') {
|
|
// Place logs in storage/logs/ at the project root
|
|
$this->logFile = __DIR__ . "/../../storage/logs/" . $filename;
|
|
}
|
|
|
|
public function log(string $message, string $level = 'INFO'): void {
|
|
$this->checkRotation();
|
|
|
|
$timestamp = date('Y-m-d H:i:s');
|
|
$formattedMessage = "[$timestamp] [$level] $message" . PHP_EOL;
|
|
|
|
file_put_contents($this->logFile, $formattedMessage, FILE_APPEND | LOCK_EX);
|
|
}
|
|
|
|
private function checkRotation(): void {
|
|
if (file_exists($this->logFile) && filesize($this->logFile) >= $this->maxSize) {
|
|
$this->rotate();
|
|
}
|
|
}
|
|
|
|
private function rotate(): void {
|
|
// Delete the oldest file if it exists (e.g., app.log.5)
|
|
$oldestFile = $this->logFile . '.' . $this->maxFiles;
|
|
if (file_exists($oldestFile)) {
|
|
unlink($oldestFile);
|
|
}
|
|
|
|
// Shift existing files up (4 becomes 5, 3 becomes 4, etc.)
|
|
for ($i = $this->maxFiles - 1; $i >= 1; $i--) {
|
|
$currentFile = $this->logFile . '.' . $i;
|
|
$nextFile = $this->logFile . '.' . ($i + 1);
|
|
if (file_exists($currentFile)) {
|
|
rename($currentFile, $nextFile);
|
|
}
|
|
}
|
|
|
|
// Move the main log file to .1
|
|
rename($this->logFile, $this->logFile . '.1');
|
|
|
|
// Create a new empty log file
|
|
touch($this->logFile);
|
|
chmod($this->logFile, 0664);
|
|
}
|
|
|
|
// Shorthand helpers
|
|
public function info($msg) { $this->log($msg, 'INFO'); }
|
|
public function error($msg) { $this->log($msg, 'ERROR'); }
|
|
}
|
|
|
|
?>
|