You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
52 lines
2.3 KiB
52 lines
2.3 KiB
<?php
|
|
class Logger {
|
|
private $logPath;
|
|
private $logLevel;
|
|
private $maxFileSize;
|
|
const LEVEL_DEBUG = 'debug';
|
|
const LEVEL_INFO = 'info';
|
|
const LEVEL_WARNING = 'warning';
|
|
const LEVEL_ERROR = 'error';
|
|
private $levelPriority = [
|
|
self::LEVEL_DEBUG => 0,
|
|
self::LEVEL_INFO => 1,
|
|
self::LEVEL_WARNING => 2,
|
|
self::LEVEL_ERROR => 3
|
|
];
|
|
public function __construct($logPath, $logLevel = self::LEVEL_INFO, $maxFileSize = 10485760) {
|
|
$this->logPath = rtrim($logPath, '/') . '/';
|
|
$this->logLevel = $logLevel;
|
|
$this->maxFileSize = $maxFileSize;
|
|
if (!is_dir($this->logPath)) {
|
|
mkdir($this->logPath, 0755, true);
|
|
}
|
|
}
|
|
public function debug($message, $context = []) { $this->log(self::LEVEL_DEBUG, $message, $context); }
|
|
public function info($message, $context = []) { $this->log(self::LEVEL_INFO, $message, $context); }
|
|
public function warning($message, $context = []) { $this->log(self::LEVEL_WARNING, $message, $context); }
|
|
public function error($message, $context = []) { $this->log(self::LEVEL_ERROR, $message, $context); }
|
|
private function log($level, $message, $context = []) {
|
|
if ($this->levelPriority[$level] < $this->levelPriority[$this->logLevel]) { return; }
|
|
if (!empty($context)) {
|
|
foreach ($context as $key => $value) {
|
|
$message = str_replace('{' . $key . '}', (string)$value, $message);
|
|
}
|
|
}
|
|
$timestamp = date('Y-m-d H:i:s');
|
|
$pid = getmypid();
|
|
$ip = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
|
|
$formatted = sprintf("[%s] [%s] [PID: %d] [IP: %s] %s\n", $timestamp, strtoupper($level), $pid, $ip, $message);
|
|
$logFile = $this->logPath . date('Y-m-d') . '.log';
|
|
$this->rotate($logFile);
|
|
file_put_contents($logFile, $formatted, FILE_APPEND | LOCK_EX);
|
|
}
|
|
private function rotate($logFile) {
|
|
if (file_exists($logFile) && filesize($logFile) > $this->maxFileSize) {
|
|
$backupFile = $logFile . '.' . date('His');
|
|
rename($logFile, $backupFile);
|
|
}
|
|
}
|
|
public function setLevel($level) { if (isset($this->levelPriority[$level])) { $this->logLevel = $level; } }
|
|
public function getLevel() { return $this->logLevel; }
|
|
}
|