Table of Contents
Code implementation of PHP rolling log
Home Backend Development PHP Tutorial Code implementation of PHP rolling log_PHP tutorial

Code implementation of PHP rolling log_PHP tutorial

Jul 13, 2016 am 09:51 AM
php code accomplish I log have scroll of Class library Record

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 <= 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 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 < $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 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 <= self::LOGS_DEBUG)

{

$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 <= self::LOGS_MSG)

{

$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 <= self::LOGS_ERR)

{

$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__);

1 2

3

4

5

1

2

3

4

5

testlog_4.log

testlog_3.log

testlog_2.log

testlog_1.log

testlog.log #最新的日志在这个文件中

$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 #最新的日志在这个文件中 http://www.bkjia.com/PHPjc/1014276.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/1014276.htmlTechArticlePHP滚动日志的代码实现 PHP滚动日志类库 PHP记录日志,我之前接触过的有按照年月分文件夹,然后按照日分文件的日志记录方式,这种方式...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1248
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles