log rotation

master
Gilles Crettenand 11 years ago
parent 3e3f5c5f47
commit 80e139e018

@ -79,6 +79,37 @@ class Logger {
if(! file_exists($file)) { if(! file_exists($file)) {
mkdir(dirname($file), 0777, true); mkdir(dirname($file), 0777, true);
touch($file); touch($file);
} else {
$mtime = filemtime($file);
// start of the current day
$start = strtotime("midnight");
// log rotate if the last entry in the log is from yesterday
if($mtime < $start) {
$files = glob($file.'.?');
natsort($files);
$files = array_reverse($files);
$files[] = $file;
// we count before adding the next file
$len = count($files);
$next = intval(substr($files[0], -1)) + 1;
$next = $next == 1 ? "$file.1" : substr($files[0], 0, -1).$next;
array_unshift($files, $next);
for($i = 0; $i < $len; ++$i) {
// move all the log files to the next name
rename($files[$i + 1], $files[$i]);
}
// delete all files with a number bigger than 9
$files = glob($file.'.??');
array_map('unlink', $files);
// recreate the new log file
touch($file);
}
} }
file_put_contents($file, $msg, FILE_APPEND | LOCK_EX); file_put_contents($file, $msg, FILE_APPEND | LOCK_EX);
} }

Loading…
Cancel
Save