| final class LOGS { private $level; private $maxFileNum; private $maxFileSize; private $logPath; private $file; //日誌的層級DEBUG,MSG,ERR const LOGS_DEBUG = 0; const LOGS_MSG = 1; const LOGS_ERR = 2; private static $instance = null; private function __construct(){} public static function getInstance() { if(self::$instance == null) { self::$instance = new self(); } return self::$instance; } /** * @Desc 初始化 * @Param $level int 記錄層級 * @Param $maxNum int 最大記錄檔數目 * @Param $maxSize int 最大記錄檔大小 * @Param $logPath string 記錄檔儲存路徑 * @Param $file string 記錄檔名稱首碼 * @Return boolean */ public function init($level, $maxNum, $maxSize, $logPath, $file) { $level = intval($level); $maxNum = intval($maxNum); $maxSize = intval($maxSize); !is_dir($logPath) && mkdir($logPath, 0777, true); if(!in_array($level, array(self::LOGS_DEBUG, self::LOGS_MSG, self::LOGS_ERR)) || $maxNum <= 0 || $maxSize <= 0 || !is_dir($logPath)) { return false; } $this->level = $level; $this->maxFileNum = $maxNum; $this->maxFileSize = $maxSize; $this->logPath = $logPath; $this->file = $file; return true; } /** * @Desc 擷取格式化時間串 */ public function formatTime() { $ustime = explode ( " ", microtime () ); return "[" . date('Y-m-d H:i:s', time()) .".". ($ustime[0] * 1000) . "]"; } /** * @Desc 滾動方式記錄記錄檔 */ public function log($str) { $path = $this->logPath.DIRECTORY_SEPARATOR.$this->file.".log"; clearstatcache(); if(file_exists($path)) { if(filesize($path) >= $this->maxFileSize) { $index = 1; //擷取最大的滾動日誌數目 for(;$index < $this->maxFileNum; $index++) { if(!file_exists($this->logPath.DIRECTORY_SEPARATOR.$this->file."_".$index.".log")) { break; } } //已經存在maxFileNum個記錄檔了 if($index == $this->maxFileNum) { $index--; } //滾動日誌 for(;$index > 1; $index--) { $new = $this->logPath.DIRECTORY_SEPARATOR.$this->file."_".$index.".log"; $old = $this->logPath.DIRECTORY_SEPARATOR.$this->file."_".($index - 1).".log"; rename($old, $new); } $newFile = $this->logPath.DIRECTORY_SEPARATOR.$this->file."_1.log"; rename($path, $newFile); } } $fp = fopen($path, "a+b"); fwrite($fp, $str, strlen($str)); fclose($fp); return true; } /** * @Desc 記錄調試資訊 * @Param string 日誌資訊 * @Param string 日誌所在檔案 * @Param string 日誌所在行 */ public function debug($msg, $file, $line) { if($this->level <= self::LOGS_DEBUG) { $this->log($this->formatTime()."[{$file}:{$line}]DEBUG: ${msg}\n"); } } /** * @Desc 記錄資訊 * @Param string 日誌資訊 * @Param string 日誌所在檔案 * @Param string 日誌所在行 */ public function msg($msg, $file, $line) { if($this->level <= self::LOGS_MSG) { $this->log($this->formatTime()."[{$file}:{$line}]MSG: ${msg}\n"); } } /** * @Desc 記錄錯誤資訊 * @Param string 日誌資訊 * @Param string 日誌所在檔案 * @Param string 日誌所在行 */ public function err($msg, $file, $line) { if($this->level <= self::LOGS_ERR) { $this->log($this->formatTime()."[{$file}:{$line}]ERR: ${msg}\n"); } } } |