Welcome Guest, Not a member yet? Register   Sign In
Log maintenance library
#1

[eluser]deadelvis[/eluser]
... 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:
Code:
// 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:
Code:
<?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 (  substr( strtolower($file), -4, 4 )=='.php' && substr( strtolower($file), 0, 3 )=='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>0 ){
            log_message('info', $total.' log files: '.$deleted.' deleted, '.$kept.' kept.');
        }
        $a = array('total'=>$total, 'deleted'=>$deleted, 'kept'=>$kept);
        return $a;
    }
}

?&gt;

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.
#2

[eluser]IamPrototype[/eluser]
Looks great. Smile
#3

[eluser]marinaccio[/eluser]
Thanks, this will definitely come in handy!
#4

[eluser]Brian Nowell[/eluser]
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.

Code:
&lt;?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 (  substr( strtolower($file), -4, 4 )=='.php' && substr( strtolower($file), 0, 3 )=='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>0 ){
            log_message('info', $total.' log files: '.$deleted.' deleted, '.$kept.' kept.');
        }
        $a = array('total'=>$total, 'deleted'=>$deleted, 'kept'=>$kept);
        return $a;
    }
}
#5

[eluser]CodeIgniteMe[/eluser]
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!
#6

[eluser]deadelvis[/eluser]
Thanks Brian... Noticed the same problem and solved it with...
Code:
$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
#7

[eluser]CodeIgniteMe[/eluser]
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.
Code:
/*
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

*/
&lt;?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;
    }
}
#8

[eluser]Binod Kumar Luitel[/eluser]
Here is a little of my contribution to Codeigniter:
Code:
&lt;?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 > 0 ){
   log_message('info', $total.' log files: '.$deleted.' deleted, '.$kept.' kept.');
  }
  $a = array('total' => $total, 'deleted' => $deleted, 'kept' => $kept);
  return $a;
}
}
#9

[eluser]quickshiftin[/eluser]
Good stuff guys, very useful!
#10

[eluser]od3n[/eluser]
many thanks!




Theme © iAndrew 2016 - Forum software by © MyBB