1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
| <?php
class Logger { const EMERGENCY = 'emergency'; const ALERT = 'alert'; const CRITICAL = 'critical'; const ERROR = 'error'; const WARNING = 'warning'; const NOTICE = 'notice'; const INFO = 'info'; const DEBUG = 'debug'; private $logFile; private $logLevel; private $dateFormat; private $maxFileSize; private $maxFiles; private static $levels = [ self::EMERGENCY => 0, self::ALERT => 1, self::CRITICAL => 2, self::ERROR => 3, self::WARNING => 4, self::NOTICE => 5, self::INFO => 6, self::DEBUG => 7 ]; public function __construct($logFile = 'app.log', $logLevel = self::INFO, $dateFormat = 'Y-m-d H:i:s') { $this->logFile = $logFile; $this->logLevel = $logLevel; $this->dateFormat = $dateFormat; $this->maxFileSize = 10 * 1024 * 1024; $this->maxFiles = 5; $logDir = dirname($this->logFile); if (!is_dir($logDir)) { mkdir($logDir, 0755, true); } } public function log($level, $message, array $context = []) { if (!$this->shouldLog($level)) { return; } $this->rotateLogIfNeeded(); $timestamp = date($this->dateFormat); $levelUpper = strtoupper($level); $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2); $caller = $backtrace[1] ?? $backtrace[0]; $file = basename($caller['file'] ?? 'unknown'); $line = $caller['line'] ?? 'unknown'; $contextStr = ''; if (!empty($context)) { $contextStr = ' ' . json_encode($context, JSON_UNESCAPED_UNICODE); } $logEntry = sprintf( "[%s] %s: %s (%s:%s)%s\n", $timestamp, $levelUpper, $message, $file, $line, $contextStr ); file_put_contents($this->logFile, $logEntry, FILE_APPEND | LOCK_EX); } public function emergency($message, array $context = []) { $this->log(self::EMERGENCY, $message, $context); } public function alert($message, array $context = []) { $this->log(self::ALERT, $message, $context); } public function critical($message, array $context = []) { $this->log(self::CRITICAL, $message, $context); } public function error($message, array $context = []) { $this->log(self::ERROR, $message, $context); } public function warning($message, array $context = []) { $this->log(self::WARNING, $message, $context); } public function notice($message, array $context = []) { $this->log(self::NOTICE, $message, $context); } public function info($message, array $context = []) { $this->log(self::INFO, $message, $context); } public function debug($message, array $context = []) { $this->log(self::DEBUG, $message, $context); } private function shouldLog($level) { return self::$levels[$level] <= self::$levels[$this->logLevel]; } private function rotateLogIfNeeded() { if (!file_exists($this->logFile)) { return; } if (filesize($this->logFile) < $this->maxFileSize) { return; } for ($i = $this->maxFiles - 1; $i > 0; $i--) { $oldFile = $this->logFile . '.' . $i; $newFile = $this->logFile . '.' . ($i + 1); if (file_exists($oldFile)) { if ($i == $this->maxFiles - 1) { unlink($oldFile); } else { rename($oldFile, $newFile); } } } rename($this->logFile, $this->logFile . '.1'); } public function tail($lines = 50) { if (!file_exists($this->logFile)) { return []; } $file = new SplFileObject($this->logFile); $file->seek(PHP_INT_MAX); $totalLines = $file->key(); $startLine = max(0, $totalLines - $lines); $logs = []; $file->seek($startLine); while (!$file->eof()) { $line = trim($file->current()); if (!empty($line)) { $logs[] = $line; } $file->next(); } return $logs; } public function search($pattern, $maxResults = 100) { if (!file_exists($this->logFile)) { return []; } $results = []; $count = 0; $handle = fopen($this->logFile, 'r'); if ($handle) { while (($line = fgets($handle)) !== false && $count < $maxResults) { if (preg_match($pattern, $line)) { $results[] = trim($line); $count++; } } fclose($handle); } return $results; } }
$logger = new Logger('logs/application.log', Logger::DEBUG);
$logger->info('应用程序启动', ['version' => '1.0.0', 'environment' => 'development']); $logger->debug('调试信息', ['user_id' => 123, 'action' => 'login']); $logger->warning('警告信息', ['memory_usage' => '85%']); $logger->error('错误信息', ['error_code' => 500, 'message' => '数据库连接失败']);
echo "最近的日志记录:\n"; $recentLogs = $logger->tail(5); foreach ($recentLogs as $log) { echo $log . "\n"; }
echo "\n错误日志:\n"; $errorLogs = $logger->search('/ERROR:/', 10); foreach ($errorLogs as $log) { echo $log . "\n"; } ?>
|