PHP滚动日志的代码实现
PHP滚动日志的代码实现
PHP滚动日志类库
PHP记录日志,我之前接触过的有按照年月分文件夹,然后按照日分文件的日志记录方式,这种方式有利有弊,有他的使用场景,我今天要说的是另一种日志记录方式——文件滚动方式记录日志,当然了,这种滚动机制也可以加在前面那种日志记录方式中。
如何让日志滚动起来
滚动日志,顾名思义,记录一个模块的日志用一系列的日志文件,同一模块文件个数有限制,最多maxNum个,大小也有限制,最大maxSize字节,文件名有一定的命名方式,比如:testlog.log、testlog_1.log,testlog_2.log、、、、、、其中testlog.log是正在使用的日志文件,当testlog.log文件大小到达限制maxSize的时候就会向后滚动日志文件,就像下面这样:
代码如下:
testlog_2.log -> testlog_3.log
testlog_1.log -> testlog_2.log
testlog.log -> testlog_1.log
testlog.log #0kb
当日志文件个数到达限制maxNum的时候就会启动淘汰机制,删除最老的日志,比如说maxNum设置为10,这个时候算上testlog.log一共最多有10个文件,当滚动的时候如果存在testlog_9.log就会从testlog_8.log开始滚动,覆盖掉testlog_9.log,这样就可以保证日志正常记录,而且不会出现很大很大的日志文件,保证日志系统的正常运行。
代码实现
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 |
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 { 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 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 { $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 { $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 { $this->log($this->formatTime()."[{$file}:{$line}]ERR: ${msg}\n"); } } } |
看个例子
#例子中设置记录级别为msg(此时debug信息是不会纪录的),日志文件个数为5,大小为200个字节(测试方便),文件名称为testlog
1 2 3 4 5 |
$logs = LOGS::getInstance(); $logs->init(1, 5, 200, "./", 'testlog');
$logs->msg("YRT", __FILE__, __LINE__); $logs->debug("YRT", __FILE__, __LINE__); |
当我们不停的运行这个例子的时候,会在代码所在文件夹下生成5个文件就像下面这样:
1 2 3 4 5 |
testlog_4.log testlog_3.log testlog_2.log testlog_1.log testlog.log #最新的日志在这个文件中 |

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











PHP 8.4는 상당한 양의 기능 중단 및 제거를 통해 몇 가지 새로운 기능, 보안 개선 및 성능 개선을 제공합니다. 이 가이드에서는 Ubuntu, Debian 또는 해당 파생 제품에서 PHP 8.4를 설치하거나 PHP 8.4로 업그레이드하는 방법을 설명합니다.

CakePHP는 PHP용 오픈 소스 프레임워크입니다. 이는 애플리케이션을 훨씬 쉽게 개발, 배포 및 유지 관리할 수 있도록 하기 위한 것입니다. CakePHP는 강력하고 이해하기 쉬운 MVC와 유사한 아키텍처를 기반으로 합니다. 모델, 뷰 및 컨트롤러 gu

VS Code라고도 알려진 Visual Studio Code는 모든 주요 운영 체제에서 사용할 수 있는 무료 소스 코드 편집기 또는 통합 개발 환경(IDE)입니다. 다양한 프로그래밍 언어에 대한 대규모 확장 모음을 통해 VS Code는

CakePHP는 오픈 소스 MVC 프레임워크입니다. 이를 통해 애플리케이션 개발, 배포 및 유지 관리가 훨씬 쉬워집니다. CakePHP에는 가장 일반적인 작업의 과부하를 줄이기 위한 여러 라이브러리가 있습니다.

이 튜토리얼은 PHP를 사용하여 XML 문서를 효율적으로 처리하는 방법을 보여줍니다. XML (Extensible Markup Language)은 인간의 가독성과 기계 구문 분석을 위해 설계된 다목적 텍스트 기반 마크 업 언어입니다. 일반적으로 데이터 저장 AN에 사용됩니다
