Skip to content

Commit 4ab27ca

Browse files
committed
Implemented log file rotation.
1 parent ef59236 commit 4ab27ca

File tree

2 files changed

+219
-37
lines changed

2 files changed

+219
-37
lines changed

lib/Cake/Log/Engine/FileLog.php

Lines changed: 124 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020

2121
App::uses('BaseLog', 'Log/Engine');
2222
App::uses('Hash', 'Utility');
23+
App::uses('CakeNumber', 'Utility');
2324

2425
/**
2526
* File Storage stream for Logging. Writes logs to different files
@@ -29,39 +30,92 @@
2930
*/
3031
class FileLog extends BaseLog {
3132

33+
/**
34+
* Default configuration values
35+
*
36+
* @var array
37+
* @see FileLog::__construct()
38+
*/
39+
protected $_defaults = array(
40+
'path' => LOGS,
41+
'file' => null,
42+
'types' => null,
43+
'scopes' => array(),
44+
'rotate' => 10,
45+
'size' => 10485760 // 10MB
46+
);
47+
3248
/**
3349
* Path to save log files on.
3450
*
3551
* @var string
3652
*/
3753
protected $_path = null;
3854

55+
/**
56+
* Log file name
57+
*
58+
* @var string
59+
*/
60+
protected $_file = null;
61+
62+
/**
63+
* Max file size, used for log file rotation.
64+
*
65+
* @var integer
66+
*/
67+
protected $_size = null;
68+
3969
/**
4070
* Constructs a new File Logger.
4171
*
4272
* Config
4373
*
4474
* - `types` string or array, levels the engine is interested in
4575
* - `scopes` string or array, scopes the engine is interested in
46-
* - `file` log file name
47-
* - `path` the path to save logs on.
76+
* - `file` Log file name
77+
* - `path` The path to save logs on.
78+
* - `size` Used to implement basic log file rotation. If log file size
79+
* reaches specified size the existing file is renamed by appending timestamp
80+
* to filename and new log file is created. Can be integer bytes value or
81+
* human reabable string values like '10MB', '100KB' etc.
82+
* - `rotate` Log files are rotated specified times before being removed.
83+
* If value is 0, old versions are removed rather then rotated.
4884
*
4985
* @param array $options Options for the FileLog, see above.
5086
*/
5187
public function __construct($config = array()) {
88+
$config = Hash::merge($this->_defaults, $config);
5289
parent::__construct($config);
53-
$config = Hash::merge(array(
54-
'path' => LOGS,
55-
'file' => null,
56-
'types' => null,
57-
'scopes' => array(),
58-
), $this->_config);
59-
$config = $this->config($config);
60-
$this->_path = $config['path'];
61-
$this->_file = $config['file'];
62-
if (!empty($this->_file) && !preg_match('/\.log$/', $this->_file)) {
63-
$this->_file .= '.log';
90+
}
91+
92+
/**
93+
* Sets protected properties based on config provided
94+
*
95+
* @param array $config Engine configuration
96+
* @return array
97+
*/
98+
public function config($config = array()) {
99+
parent::config($config);
100+
101+
if (!empty($config['path'])) {
102+
$this->_path = $config['path'];
103+
}
104+
if (!empty($config['file'])) {
105+
$this->_file = $config['file'];
106+
if (substr($this->_file, -4) !== '.log') {
107+
$this->_file .= '.log';
108+
}
109+
}
110+
if (!empty($config['size'])) {
111+
if (is_numeric($config['size'])) {
112+
$this->_size = (int)$config['size'];
113+
} else {
114+
$this->_size = CakeNumber::fromReadableSize($config['size']);
115+
}
64116
}
117+
118+
return $this->_config;
65119
}
66120

67121
/**
@@ -72,21 +126,70 @@ public function __construct($config = array()) {
72126
* @return boolean success of write.
73127
*/
74128
public function write($type, $message) {
129+
$output = date('Y-m-d H:i:s') . ' ' . ucfirst($type) . ': ' . $message . "\n";
130+
$filename = $this->_getFilename($type);
131+
if (!empty($this->_size)) {
132+
$this->_rotateFile($filename);
133+
}
134+
135+
return file_put_contents($this->_path . $filename, $output, FILE_APPEND);
136+
}
137+
138+
/**
139+
* Get filename
140+
* @param string $type The type of log.
141+
* @return string File name
142+
*/
143+
protected function _getFilename($type) {
75144
$debugTypes = array('notice', 'info', 'debug');
76145

77146
if (!empty($this->_file)) {
78-
$filename = $this->_path . $this->_file;
147+
$filename = $this->_file;
79148
} elseif ($type == 'error' || $type == 'warning') {
80-
$filename = $this->_path . 'error.log';
149+
$filename = 'error.log';
81150
} elseif (in_array($type, $debugTypes)) {
82-
$filename = $this->_path . 'debug.log';
83-
} elseif (in_array($type, $this->_config['scopes'])) {
84-
$filename = $this->_path . $this->_file;
151+
$filename = 'debug.log';
85152
} else {
86-
$filename = $this->_path . $type . '.log';
153+
$filename = $type . '.log';
87154
}
88-
$output = date('Y-m-d H:i:s') . ' ' . ucfirst($type) . ': ' . $message . "\n";
89-
return file_put_contents($filename, $output, FILE_APPEND);
155+
156+
return $filename;
157+
}
158+
159+
/**
160+
* Rotate log file if size specified in config is reached.
161+
* Also if `rotate` count is reached oldest file is removed.
162+
*
163+
* @param string $filename Log file name
164+
* @return mixed True if rotated successfully or false in case of error.
165+
* Void if file doesn't need to be rotated.
166+
*/
167+
protected function _rotateFile($filename) {
168+
$filepath = $this->_path . $filename;
169+
if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
170+
clearstatcache(true, $filepath);
171+
} else {
172+
clearstatcache();
173+
}
174+
175+
if (!file_exists($filepath) ||
176+
filesize($filepath) < $this->_size
177+
) {
178+
return;
179+
}
180+
181+
if ($this->_config['rotate'] === 0) {
182+
return unlink($filepath);
183+
}
184+
185+
if ($this->_config['rotate']) {
186+
$files = glob($filepath . '.*');
187+
if (count($files) === $this->_config['rotate']) {
188+
unlink(array_shift($files));
189+
}
190+
}
191+
192+
return rename($filepath, $filepath . '.' . time());
90193
}
91194

92195
}

lib/Cake/Test/Case/Log/Engine/FileLogTest.php

Lines changed: 95 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -32,36 +32,26 @@ class FileLogTest extends CakeTestCase {
3232
* @return void
3333
*/
3434
public function testLogFileWriting() {
35-
if (file_exists(LOGS . 'error.log')) {
36-
unlink(LOGS . 'error.log');
37-
}
35+
$this->_deleteLogs(LOGS);
36+
3837
$log = new FileLog();
3938
$log->write('warning', 'Test warning');
4039
$this->assertTrue(file_exists(LOGS . 'error.log'));
4140

4241
$result = file_get_contents(LOGS . 'error.log');
4342
$this->assertRegExp('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Warning: Test warning/', $result);
44-
unlink(LOGS . 'error.log');
4543

46-
if (file_exists(LOGS . 'debug.log')) {
47-
unlink(LOGS . 'debug.log');
48-
}
4944
$log->write('debug', 'Test warning');
5045
$this->assertTrue(file_exists(LOGS . 'debug.log'));
5146

5247
$result = file_get_contents(LOGS . 'debug.log');
5348
$this->assertRegExp('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Debug: Test warning/', $result);
54-
unlink(LOGS . 'debug.log');
5549

56-
if (file_exists(LOGS . 'random.log')) {
57-
unlink(LOGS . 'random.log');
58-
}
5950
$log->write('random', 'Test warning');
6051
$this->assertTrue(file_exists(LOGS . 'random.log'));
6152

6253
$result = file_get_contents(LOGS . 'random.log');
6354
$this->assertRegExp('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Random: Test warning/', $result);
64-
unlink(LOGS . 'random.log');
6555
}
6656

6757
/**
@@ -71,14 +61,103 @@ public function testLogFileWriting() {
7161
*/
7262
public function testPathSetting() {
7363
$path = TMP . 'tests' . DS;
74-
if (file_exists(LOGS . 'error.log')) {
75-
unlink(LOGS . 'error.log');
76-
}
64+
$this->_deleteLogs($path);
7765

7866
$log = new FileLog(compact('path'));
7967
$log->write('warning', 'Test warning');
8068
$this->assertTrue(file_exists($path . 'error.log'));
81-
unlink($path . 'error.log');
69+
}
70+
71+
/**
72+
* test log rotation
73+
*
74+
* @return void
75+
*/
76+
public function testRotation() {
77+
$path = TMP . 'tests' . DS;
78+
$this->_deleteLogs($path);
79+
80+
file_put_contents($path . 'error.log', "this text is under 35 bytes\n");
81+
$log = new FileLog(array(
82+
'path' => $path,
83+
'size' => 35,
84+
'rotate' => 2
85+
));
86+
$log->write('warning', 'Test warning one');
87+
$this->assertTrue(file_exists($path . 'error.log'));
88+
89+
$result = file_get_contents($path . 'error.log');
90+
$this->assertRegExp('/Warning: Test warning one/', $result);
91+
$this->assertEquals(0, count(glob($path . 'error.log.*')));
92+
93+
clearstatcache();
94+
$log->write('warning', 'Test warning second');
95+
96+
$files = glob($path . 'error.log.*');
97+
$this->assertEquals(1, count($files));
98+
99+
$result = file_get_contents($files[0]);
100+
$this->assertRegExp('/this text is under 35 bytes/', $result);
101+
$this->assertRegExp('/Warning: Test warning one/', $result);
102+
103+
sleep(1);
104+
clearstatcache();
105+
$log->write('warning', 'Test warning third');
106+
107+
$result = file_get_contents($path . 'error.log');
108+
$this->assertRegExp('/Warning: Test warning third/', $result);
109+
110+
$files = glob($path . 'error.log.*');
111+
$this->assertEquals(2, count($files));
112+
113+
$result = file_get_contents($files[0]);
114+
$this->assertRegExp('/this text is under 35 bytes/', $result);
115+
116+
$result = file_get_contents($files[1]);
117+
$this->assertRegExp('/Warning: Test warning second/', $result);
118+
119+
sleep(1);
120+
clearstatcache();
121+
$log->write('warning', 'Test warning fourth');
122+
123+
// rotate count reached so file count should not increase
124+
$files = glob($path . 'error.log.*');
125+
$this->assertEquals(2, count($files));
126+
127+
$result = file_get_contents($path . 'error.log');
128+
$this->assertRegExp('/Warning: Test warning fourth/', $result);
129+
130+
$result = file_get_contents(array_pop($files));
131+
$this->assertRegExp('/Warning: Test warning third/', $result);
132+
133+
$result = file_get_contents(array_pop($files));
134+
$this->assertRegExp('/Warning: Test warning second/', $result);
135+
136+
file_put_contents($path . 'debug.log', "this text is just greater than 35 bytes\n");
137+
$log = new FileLog(array(
138+
'path' => $path,
139+
'size' => 35,
140+
'rotate' => 0
141+
));
142+
$log->write('debug', 'Test debug');
143+
$this->assertTrue(file_exists($path . 'debug.log'));
144+
145+
$result = file_get_contents($path . 'debug.log');
146+
$this->assertRegExp('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Debug: Test debug/', $result);
147+
$this->assertFalse(strstr($result, 'greater than 5 bytes'));
148+
$this->assertEquals(0, count(glob($path . 'debug.log.*')));
149+
}
150+
151+
/**
152+
* helper function to clears all log files in specified directory
153+
*
154+
* @return void
155+
*/
156+
protected function _deleteLogs($dir) {
157+
$files = array_merge(glob($dir . '*.log'), glob($dir . '*.log.*'));
158+
foreach ($files as $file) {
159+
unlink($file);
160+
}
82161
}
83162

84163
}

0 commit comments

Comments
 (0)