54 lines
		
	
	
		
			1.3 KiB
		
	
	
	
		
			PHP
		
	
	
	
	
	
			
		
		
	
	
			54 lines
		
	
	
		
			1.3 KiB
		
	
	
	
		
			PHP
		
	
	
	
	
	
<?php
 | 
						|
class Logger {
 | 
						|
    protected string $logFile;
 | 
						|
    protected int $logLevelThreshold;
 | 
						|
 | 
						|
    const LEVELS = [
 | 
						|
        'DEBUG' => 0,
 | 
						|
        'INFO' => 1,
 | 
						|
        'WARNING' => 2,
 | 
						|
        'ERROR' => 3,
 | 
						|
        'NONE' => 999
 | 
						|
    ];
 | 
						|
 | 
						|
    public function __construct(string $logFile, string $minLevel = 'DEBUG') {
 | 
						|
        $this->logFile = $logFile;
 | 
						|
        $minLevel = strtoupper($minLevel);
 | 
						|
        $this->logLevelThreshold = self::LEVELS[$minLevel] ?? 0;
 | 
						|
    }
 | 
						|
 | 
						|
    protected function log(string $level, string $message): void {
 | 
						|
        $level = strtoupper($level);
 | 
						|
        if (!isset(self::LEVELS[$level]) || self::LEVELS[$level] < $this->logLevelThreshold) {
 | 
						|
            return;
 | 
						|
        }
 | 
						|
 | 
						|
        $time = date('Y-m-d H:i:s');
 | 
						|
        $ip = $_SERVER['REMOTE_ADDR'];
 | 
						|
        $logEntry = "[$time] [$ip] [$level] $message" . PHP_EOL;
 | 
						|
 | 
						|
        file_put_contents($this->logFile, $logEntry, FILE_APPEND | LOCK_EX);
 | 
						|
    }
 | 
						|
 | 
						|
    public function debug(string $msg): void {
 | 
						|
        $this->log('DEBUG', $msg);
 | 
						|
    }
 | 
						|
 | 
						|
    public function info(string $msg): void {
 | 
						|
        $this->log('INFO', $msg);
 | 
						|
    }
 | 
						|
 | 
						|
    public function warning(string $msg): void {
 | 
						|
        $this->log('WARNING', $msg);
 | 
						|
    }
 | 
						|
 | 
						|
    // Alias
 | 
						|
    public function warn(string $msg): void {
 | 
						|
        $this->log('WARNING', $msg);
 | 
						|
    }
 | 
						|
 | 
						|
    public function error(string $msg): void {
 | 
						|
        $this->log('ERROR', $msg);
 | 
						|
    }
 | 
						|
}
 |