EllisLab text mark
Advanced Search
     
Log maintenance library
Posted: 22 June 2009 08:42 PM
Avatar
Joined: 2007-07-14
28 posts

... or actually just a quick way to get rid of the growing number of log files (my website constantly logs info messages for performance monitoring), by just deleting the old ones.

Add this to your config:

// Log_maintenance library: how many days to keep log files
$config['log_days_to_keep'15

Save this as Log_maintenance.php in your libraries folder:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class 
Log_maintenance {

    
function Log_maintenance(){
        $this
->CI =& get_instance();
        
$this->log_days_to_keep $this->CI->config->item('log_days_to_keep');
        
$this->delete_old_logs(); // delete the old log files
    
}
    
    
function delete_old_logs(){
        $dir 
$this->CI->config->item('log_path');
        if( !
is_dir($dir) )return false}
        $dh 
opendir($dir);
        
$deleted 0;
        
$kept 0;
        while ( (
$file readdir($dh)) !== false){
            
// check log filename: log*.php
            
if (  substrstrtolower($file), -4)=='.php' && substrstrtolower($file), 0)=='log'){
                
// check how old they are
                
if( filemtime($dir.$file) < strtotime('-'.$this->log_days_to_keep.' days') ) {
                    unlink($dir
.$file);
                    
$deleted++;
                
}else{
                    $kept
++;
                
}
            }
        }
        closedir
($dh);
        
$total $deleted+$kept;
        if( 
$deleted>){
            log_message
('info'$total.' log files: '.$deleted.' deleted, '.$kept.' kept.');
        
}
        $a 
= array('total'=>$total'deleted'=>$deleted'kept'=>$kept);
        return 
$a;
    
}
}

?> 

Just load the library somewhere in your code to have the old log files deleted.


It’s my first library… so do review the code if you plan on using. Any comments/improvements/suggestions are very much welcome.

 Signature 

feedbleed.com - Saving music… one download at a time.
mmmmail.com - Disposable Email to RSS service.

 
Posted: 23 June 2009 05:55 AM   [ # 1 ]   [ Rating: 0 ]
Joined: 2008-12-27
170 posts

Looks great. smile

 Signature 

Greetings from Denmark!

 
Posted: 17 July 2009 12:13 AM   [ # 2 ]   [ Rating: 0 ]
Avatar
Joined: 2007-03-09
25 posts

Thanks, this will definitely come in handy!

 Signature 

-
Joseph Marinaccio
.(JavaScript must be enabled to view this email address) | web dev

 
Posted: 07 August 2011 12:17 PM   [ # 3 ]   [ Rating: 0 ]
Joined: 2006-11-29
2 posts

I found that this lib didn’t work when [log_path] config var was blank. So added some code from the system/libraries/log.php file to test for blank and default. Anyway, quick and dirty.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class 
Log_maintenance {
/*
Updated by: Brian Nowell
Date:       08/07/2011

Description: Did not work when log_path config var was blank. Added code from System/Libraries/Log.php
to check for blank path and replace with default value. Library will keep current day plus number of [log_days_to_keep]
value.

Usage: Add this to Config.php

// Log_maintenance library: how many days to keep log files
$config['log_days_to_keep'] = 15;   // will keep 16 files

*/
    
function Log_maintenance(){
        log_message
('debug','Log_Maintenance : class loaded');
        
$this->CI =& get_instance();
        
$this->log_days_to_keep $this->CI->config->item('log_days_to_keep');
        
$this->delete_old_logs(); // delete the old log files
    
}

    
function delete_old_logs(){

        $dir 
$this->CI->config->item('log_path');
        
$dir = ($dir != '') ? $dir BASEPATH.'logs/';

        
log_message('debug','Log_Maintenance : log dir: '.$dir);

        if( ! 
is_dir($dir) OR ! is_really_writable($dir))return false}

        $dh 
opendir($dir);
        
$deleted 0;
        
$kept 0;
        while ( (
$file readdir($dh)) !== false){
            
// check log filename: log*.php
            
if (  substrstrtolower($file), -4)=='.php' && substrstrtolower($file), 0)=='log'){
                
// check how old they are
                
if( filemtime($dir.$file) < strtotime('-'.$this->log_days_to_keep.' days') ) {
                    unlink($dir
.$file);
                    
$deleted++;
                
}else{
                    $kept
++;
                
}
            }
        }
        closedir
($dh);
        
$total $deleted+$kept;
        if( 
$deleted>){
            log_message
('info'$total.' log files: '.$deleted.' deleted, '.$kept.' kept.');
        
}
        $a 
= array('total'=>$total'deleted'=>$deleted'kept'=>$kept);
        return 
$a;
    
}
 
Posted: 07 August 2011 11:12 PM   [ # 4 ]   [ Rating: 0 ]
Joined: 2010-12-23
254 posts

Great job, and will really be very handy. I’ll just have to modify some codes to make it work on php 5.3. Thanks!

 Signature 

Half the battle is won by following The User Guide. cool grin

 
Posted: 09 August 2011 04:07 AM   [ # 5 ]   [ Rating: 0 ]
Avatar
Joined: 2007-07-14
28 posts

Thanks Brian… Noticed the same problem and solved it with…

$dir = ($this->CI->config->item('log_path') != '') ? $this->CI->config->item('log_path') : APPPATH.'logs/'

but forgot to post it here.

CodeIgniteMe: Please post any improvements too.

Cheers

 Signature 

feedbleed.com - Saving music… one download at a time.
mmmmail.com - Disposable Email to RSS service.

 
Posted: 09 August 2011 05:58 AM   [ # 6 ]   [ Rating: 0 ]
Joined: 2010-12-23
254 posts

Made the script fully compatible with PHP >= 5.0 (as what CI >= 2.0 did), shorten the script, checked if log_days_to_keep is numeric before continuing.

/*
Updated by: CodeIgniteMe
Date:       08/09/2011

Description: checks if log_days_to_keep is numeric before assigning it to a property
Uses the native "glob" function to get the matching needed files instead of the if statement.

Updated by: Brian Nowell
Date:       08/07/2011

Description: Did not work when log_path config var was blank. Added code from System/Libraries/Log.php
to check for blank path and replace with default value. Library will keep current day plus number of [log_days_to_keep]
value.

Usage: Add this to Config.php

// Log_maintenance library: how many days to keep log files
$config['log_days_to_keep'] = 15;   // will keep 16 files

*/
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class 
Log_maintenance {
    
function __construct(){
        log_message
('debug','Log_Maintenance : class loaded');
        
$this->CI =& get_instance();
        
// check whether the config is a numeric number before assigning
        
$this->log_days_to_keep = (int) (is_numeric($this->CI->config->item('log_days_to_keep')) ? $this->CI->config->item('log_days_to_keep') : 30);
        
$this->delete_old_logs(); // delete the old log files
    
}

    
function delete_old_logs(){

        $dir 
= ($this->CI->config->item('log_path') != '') ? $this->CI->config->item('log_path') : APPPATH.'logs/';
        
// this can be:
        // $dir = ($this->CI->config->item('log_path') ?: APPPATH.'logs/');
        // ternary shorthand if operator (for PHP >= 5.3 only)

        
log_message('debug','Log_Maintenance : log dir: '.$dir);
        
        if( ! 
is_dir($dir) OR ! is_really_writable($dir))return false}

        $deleted 
0;
        
$kept 0;
        
        
$files glob($dir 'log*.php'); // all files in the directory that starts with 'log' and ends with '.php'

        
foreach($files as $file)// loop over all matched files
            // check how old they are
            
if( filemtime($file) < strtotime('-'.$this->log_days_to_keep.' days') ) //strtotime('-'.$this->log_days_to_keep.' days')
                
unlink($file);
                
$deleted++;
            
}else{
                $kept
++;
            
}
        }
        $total 
$deleted+$kept;
        if( 
$deleted>0 ){
            log_message
('info'$total.' log files: '.$deleted.' deleted, '.$kept.' kept.');
        
}
        $a 
= array('total'=>$total'deleted'=>$deleted'kept'=>$kept);
        return 
$a;
    
}
 Signature 

Half the battle is won by following The User Guide. cool grin

 
Posted: 28 May 2013 11:17 PM   [ # 7 ]   [ Rating: 0 ]
Joined: 2010-10-22
4 posts

Here is a little of my contribution to Codeigniter:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
Updated by: CodeIgniteMe
Date:       08/09/2011

Description: checks if log_days_to_keep is numeric before assigning it to a property
Uses the native "glob" function to get the matching needed files instead of the if statement.

Updated by: Brian Nowell
Date:       08/07/2011

Description: Did not work when log_path config var was blank. Added code from System/Libraries/Log.php
to check for blank path and replace with default value. Library will keep current day plus number of days to keep [logs_files_for]
value.

Updated by: Binod Luitel
Date:  05/29/2013

Description: Extends the codeigniter's Log library so that this library should not be initialized separately.
Specifying the no. of files to keep will exactly obey the rule
Works even if the config variable is not initialized within config file

Usage: Add this to Config.php

// Log_maintenance library: how many days to keep log files
$config['logs_files_for'] = 15;   // will keep 15 files

*/

class Map_Log extends CI_Log{
 
 
/**
  * No. of days until the files are deleted
 **/
 
private $logs_files_for 15;
 
    function 
__construct(){
        log_message
('debug','Log_Maintenance : class loaded');
  
  
parent::__construct($rules);
  
  
$this->CI =& get_instance();
        
// check whether the config is a numeric number before assigning
  
if(isset($this->CI->config->item('logs_files_for')))
         
$this->logs_files_for = (int) (is_numeric($this->CI->config->item('logs_files_for')) ? $this->CI->config->item('logs_files_for') : 15);
        
// delete the old log files
  
$this->delete_logs();
    
}

 
/**
  * Delete log files older than 
 **/
 
function delete_logs(){
 
  $dir 
= ($this->CI->config->item('log_path') != '') ? $this->CI->config->item('log_path') : APPPATH.'logs/';
  
// this can be:
  // $dir = ($this->CI->config->item('log_path') ?: APPPATH.'logs/');
  // ternary shorthand if operator (for PHP >= 5.3 only)
 
  
log_message('debug','Log_Maintenance : log dir: '.$dir);
  
  if( ! 
is_dir($dir) OR ! is_really_writable($dir))return false}
  
  $deleted 
0;
  
$kept 0;
  
  
$files glob($dir 'log*.php'); // all files in the directory that starts with 'log' and ends with '.php'
 
  
foreach($files as $file)// loop over all matched files
   // check how old they are
   
if( filemtime($file) < strtotime('-'.($this->logs_files_for 1).' days') ) {
    unlink($file)
;
    
$deleted++;
   
} else{
    $kept
++;
   
}
  }
  $total 
$deleted $kept;
  if( 
$deleted ){
   log_message
('info'$total.' log files: '.$deleted.' deleted, '.$kept.' kept.');
  
}
  $a 
= array('total' => $total'deleted' => $deleted'kept' => $kept);
  return 
$a;
 
}
 
Posted: 18 July 2013 02:38 AM   [ # 8 ]   [ Rating: 0 ]
Avatar
Joined: 2011-10-12
51 posts

Good stuff guys, very useful!

 
Posted: 24 July 2013 03:57 AM   [ # 9 ]   [ Rating: 0 ]
Joined: 2011-07-16
12 posts

many thanks!

 
Posted: 30 August 2013 04:48 AM   [ # 10 ]   [ Rating: 0 ]
Avatar
Joined: 2008-07-28
19 posts
Binod Kumar Luitel - 28 May 2013 11:17 PM

Here is a little of my contribution to Codeigniter:

...
 function 
__construct(){
  log_message
('debug','Log_Maintenance : class loaded');
  
parent::__construct($rules);
  
  
$this->CI =& get_instance();
        
// check whether the config is a numeric number before assigning
  
if(isset($this->CI->config->item('logs_files_for')))
         
$this->logs_files_for = (int) (is_numeric($this->CI->config->item('logs_files_for')) ? $this->CI->config->item('logs_files_for') : 15);
        
// delete the old log files
  
$this->delete_logs();
 
}
... 


Good work, I’m using it now, just one thing that I have changed for myself:

In the function __construct() because you have the default setting (private $logs_files_for = 15;) no need for more, just a cast it with a string ‘0’ before to get rid of nulls, NEGATIVE, etc… and done…

-3” IS is_numeric AND int

use this

$new_logs_files_for = (int)('0'.$this->CI->config->item('logs_files_for'));
$this->logs_files_for $new_logs_files_for>$new_logs_files_for $this->logs_files_for

or this

$new_logs_files_for = (int)('0'.$this->CI->config->item('logs_files_for'));
if(
$new_logs_files_for>0)
{
   $this
->logs_files_for $new_logs_files_for;

This way you don’t have to check if config var exists, numeric, int, etc… and only changes value IF it is greater than 0.