首頁  >  文章  >  後端開發  >  PHP滾動日誌

PHP滾動日誌

WBOY
WBOY原創
2016-08-08 09:24:231298瀏覽

PHP滾動日誌類別庫

PHP記錄日誌,我之前接觸過的有按照年月分文件夾,然後按照日分文件的日誌記錄方式,這種方式有利有弊,有他的使用場景,我今天要說的是另一種日誌記錄方式-檔案滾動方式記錄日誌,當然了,這種滾動機制也可以加在前面那種日誌記錄方式中。

如何讓日誌滾動起來

滾動日誌,顧名思義,記錄一個模組的日誌用一系列的日誌文件,同一模組文件個數有限制,最多maxNum個,大小也有限制,最大maxSize字節,文件名有一定的命名方式,比如:testlog .log、testlog_1.log,testlog_2.log、、、、、、其中testlog.log是正在使用的日誌文件,當testlog.log文件大小到達限制maxSize的時候就會向後滾動日誌文件,就像下面這樣:

<code>testlog_2.log 	-> testlog_3.log
testlog_1.log 	-> testlog_2.log
testlog.log 	-> testlog_1.log
testlog.log #0kb</code>

當日誌檔案個數到達限制maxNum的時候就會啟動淘汰機制,刪除最老的日誌,比如說maxNum設定為10,這個時候算上testlog.log一共最多有10個文件,當滾動的時候如果存在testlog_9.log就會從testlog_8.log開始滾動,覆蓋掉testlog_9.log,這樣就可以保證日誌正常記錄,而且不會出現很大很大的日誌文件,保證日誌系統的正常運作。

程式碼實作

<code><?php
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");
		}
	}
}</code>

看例子

<code>#例子中设置记录级别为msg(此时debug信息是不会纪录的),日志文件个数为5,大小为200个字节(测试方便),文件名称为testlog
$logs = LOGS::getInstance();
$logs->init(1, 5, 200, "./", 'testlog');

$logs->msg("YRT", __FILE__, __LINE__);
$logs->debug("YRT", __FILE__, __LINE__);</code>

當我們不停的運行這個例子的時候,會在程式碼所在資料夾下產生5個檔案就像下面這樣:

<code>testlog_4.log
testlog_3.log
testlog_2.log
testlog_1.log
testlog.log			#最新的日志在这个文件中</code>

以上就介紹了PHP滾動日誌,包括了方面的內容,希望對PHP教程有興趣的朋友有所幫助。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn