Iterate Log Files by Month

Here we take a log file that is set writable and iterate it by 1 at the end of every month.

First we get the time stamp of the file then we retrieve the data and format it to something more readable and compare.

$lofdir = '/path/to/log/folder/';
// get all files in the directory and place in array
if(is_dir($logdir)) {
   if ($dh = opendir($logdir)) {
       while (($loglist = readdir($dh)) !== false) {
	   		$logs[].= $loglist;
		}
	closedir($dh);
	}
}
 
 
// take the last file in the directory
$logfile = array_slice($logs, -1,1);
//print_r($logfile); // check the slice
 
 
$logfile=$logfile[0];// put into a string
$n=substr($logfile, 15); // get the number. Number may change depending on name of file
// file name : siteuptime.log.1
 
 
$path_to_log = $logdir.'/'.$logfile; // make this neat and clean in one variable
// get timestamp of current file
$timestamp= filemtime($path_to_log);
// format timestamp and get month
$timestamp = gmdate('n', $timestamp);
 
 
// if file larger then 5K = 5120b This is left if you want to rotate by size
//if(filesize($path_to_log) > 5120){ // comment out below and uncomment this line if by file size
if($timestamp != date('n')){ // if file timestamp is not equal to current month create new file
    $file=fopen($logdir.'/'.substr($logfile, 0, 15).$n+=1, "w"); // increase by 1
    chmod($file, 0777); // make writable
} else {
    $file = fopen($path_to_log, "w"); // other wise open current file
}
$fw = fwrite($file, $result); // write the results
fclose($file); // close file
 
development/php/iterate_log_flles.txt · Last modified: 2007/09/14 15:03 by vincenzobar
 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki