Code implementation of PHP rolling log
PHP rolling log library
PHP records logs. I have come across a log recording method that divides folders into folders by year and month, and then divides files into files by day. This method has advantages and disadvantages and has its usage scenarios. What I want to talk about today is another way. A logging method - file rolling method to record logs. Of course, this rolling mechanism can also be added to the previous logging method.
How to make the log scroll
Rolling log, as the name suggests, uses a series of log files to record the log of a module. The number of files in the same module is limited, up to maxNum, and the size is also limited, up to maxSize bytes. The file name has a certain naming method, such as : testlog.log, testlog_1.log, testlog_2.log,,,,,, where testlog.log is the log file in use. When the testlog.log file size reaches the limit maxSize, the log file will be rolled backwards, like As follows:
The code is as follows:
testlog_2.log -> testlog_3.log
testlog_1.log -> testlog_2.log
testlog.log -> testlog_1.log
testlog.log #0kb
When the number of log files reaches the limit maxNum, the elimination mechanism will be started and the oldest log will be deleted. For example, if maxNum is set to 10, there will be a maximum of 10 files including testlog.log at this time. When scrolling If testlog_9.log exists, it will start rolling from testlog_8.log and overwrite testlog_9.log. This ensures normal log recording and does not cause large log files to appear, ensuring the normal operation of the log system.
Code implementation
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 initialization * @Param $level int record level * @Param $maxNum int Maximum number of log files * @Param $maxSize int Maximum log file size * @Param $logPath string log file saving path * @Param $file string log file name prefix * @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 Get formatted time string */ public function formatTime() { $ustime = explode ( " ", microtime () ); return "[" . date('Y-m-d H:i:s', time()) .".". ($ustime[0] * 1000) . "]"; }
/** * @Desc rolling log file */ 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 records debugging information * @Param string log information * @Param string The file where the log is located * @Param string log line */ public function debug($msg, $file, $line) { if($this->level { $this->log($this->formatTime()."[{$file}:{$line}]DEBUG: ${msg}n"); } }
/** * @Desc record information * @Param string log information * @Param string The file where the log is located * @Param string log line */ public function msg($msg, $file, $line) { if($this->level { $this->log($this->formatTime()."[{$file}:{$line}]MSG: ${msg}n"); } }
/** * @Desc logs error messages * @Param string log information * @Param string The file where the log is located * @Param string log line */ public function err($msg, $file, $line) { if($this->level { $this->log($this->formatTime()."[{$file}:{$line}]ERR: ${msg}n"); } } } |
看个例子
#例子中设置记录级别为msg(此时debug信息是不会纪录的),日志文件个数为5,大小为200个字节(测试方便),文件名称为testlog
3 4
5
$logs = LOGS::getInstance();
$logs->init(1, 5, 200, "./", 'testlog'); |
当我们不停的运行这个例子的时候,会在代码所在文件夹下生成5个文件就像下面这样:
|

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\ \;||\xc2\xa0)/","其他字符",$str)”语句。

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

在PHP中,可以利用implode()函数的第一个参数来设置没有分隔符,该函数的第一个参数用于规定数组元素之间放置的内容,默认是空字符串,也可将第一个参数设置为空,语法为“implode(数组)”或者“implode("",数组)”。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version
Visual web development tools
