Welcome Guest, Not a member yet? Register   Sign In
Instance error logging
#1

[eluser]Lockzi[/eluser]
Hello,

let me start by saying that the name might not be appropriate to what it is doing, didn't know what to call this, one-time-run/instance/request-logger, but whatever here we go.

I got sick of having to go into todays log file (everyday) and deleting the content to easily get and distinguish the errors from a request.

Therefore I wrote an replacement for the core log class and thought I could share it.

This is optional (as variables are defined with default values in the class) and can be added anywhere in the config.php if so:

application/config/config.php
Code:
/*
|--------------------------------------------------------------------------
| Instance Error Logging
|--------------------------------------------------------------------------
|    do_instance
|     TRUE = Log this instance in separate overwrited file
|     FALSE = Do no separate log file writing
|    
|    instance_log_filename
| Leave this BLANK unless you would like to set something other than the default
| filename 'log-lastInstance' for your instance log. Do not add file extension.
|
*/
$config['do_instance'] = TRUE;
$config['instance_log_filename'] = 'log-lastInstance';
#2

[eluser]Lockzi[/eluser]
and now the library

application/libraries/Log.php
Code:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 4.3.2 or newer
*
* @package        CodeIgniter
* @author        ExpressionEngine Dev Team
* @copyright    Copyright (c) 2006, EllisLab, Inc.
* @license        http://ellislab.com/codeigniter/user-guide/license.html
* @link        http://codeigniter.com
* @since        Version 1.0
* @filesource
*/

// ------------------------------------------------------------------------

/**
* Logging Class
*
* @package        CodeIgniter
* @subpackage    Libraries
* @category    Logging
* @author        ExpressionEngine Dev Team
* @link        http://ellislab.com/codeigniter/user-guide/general/errors.html
*/
class CI_Log {

    var $log_path;
    var $_threshold    = 1;
    var $_date_fmt    = 'Y-m-d H:i:s';
    var $_enabled    = TRUE;
    var $_levels    = array('ERROR' => '1', 'DEBUG' => '2',  'INFO' => '3', 'ALL' => '4');
    var $_do_instance;
    
    var $_daylogfile;
    var $_instancelogfile;

    /**
     * Constructor
     *
     * @access    public
     */
    function CI_Log()
    {
        /**
         *    Variable defining
         */
        //Had to move the defining down here since can't set these up there *pointing*
        $this->_daylogfile = 'log-'.date('Y-m-d').EXT;
        $this->_instancelogfile = 'log-lastInstance'.EXT;
        $this->_do_instance = TRUE; //Default TRUE
        
        
        $config =& get_config();
        
        $this->log_path = ($config['log_path'] != '') ? $config['log_path'] : BASEPATH.'logs/';
        
        //Set _do_instance according to $config if it is set
        $this->_do_instance = (isset($config['do_instance'])) ? $config['do_instance'].EXT : $this->_do_instance.EXT;
        $this->_instancelogfile = (isset($config['instance_log_filename'])) ? $config['instance_log_filename'].EXT : $this->_instancelogfile.EXT;
        
        if ( ! is_dir($this->log_path) OR ! is_really_writable($this->log_path))
        {
            $this->_enabled = FALSE;
        }
        
        if (is_numeric($config['log_threshold']))
        {
            $this->_threshold = $config['log_threshold'];
        }
            
        if ($config['log_date_format'] != '')
        {
            $this->_date_fmt = $config['log_date_format'];
        }
        
        
        //If we're doing instance logging, delete the existing file to start over
        if($this->_do_instance) {
            $this->_file_delete($this->_instancelogfile);
        }
    }
    
    // --------------------------------------------------------------------
    
    /**
     * Write Log File
     *
     * Generally this function will be called using the global log_message() function
     *
     * @access    public
     * @param    string    the error level
     * @param    string    the error message
     * @param    bool    whether the error is a native PHP error
     * @return    bool
     */    
    function write_log($level = 'error', $msg, $php_error = FALSE)
    {        
        if ($this->_enabled === FALSE)
        {
            return FALSE;
        }
    
        $level = strtoupper($level);
        
        if ( ! isset($this->_levels[$level]) OR ($this->_levels[$level] > $this->_threshold))
        {
            return FALSE;
        }

        $message = $level.' '.(($level == 'INFO') ? ' -' : '-').' '.date($this->_date_fmt). ' --> '.$msg."\n";
        
        if($this->_file_write($this->_daylogfile, $message)) {
            if($this->_do_instance) {
                if( ! $this->_file_write($this->_instancelogfile, $message)) {
                    return FALSE;
                }
            }
            return TRUE;
        } else {
            return FALSE;
        }
        
    }
    
    // --------------------------------------------------------------------
    
    /**
     * File Write
     *
     * Function to open and write to the file
     *
     * @access    private
     * @param    string    the filename
     * @param    string    the full error message
     * @return    bool
     */        
    function _file_write($file, $message)
    {
        $filepath = $this->log_path.$file;
        
        if ( ! file_exists($filepath))
        {
            $fileheader = "<"."?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?".">\n\n";
            $message = $fileheader.$message;
        }
        
        if ( ! $fp = @fopen($filepath, FOPEN_WRITE_CREATE))
        {
            return FALSE;
        }
        
        
        flock($fp, LOCK_EX);    
        fwrite($fp, $message);
        flock($fp, LOCK_UN);
        fclose($fp);
    
        @chmod($filepath, FILE_WRITE_MODE);
        
        return TRUE;
    }
    
    // --------------------------------------------------------------------
    
    /**
     * File Delete
     *
     * Function to delete the instance file (can be used for other files as well)
     * in case it exists.
     *
     * Generally called from class constructor
     *
     * @access    private
     * @param    string    the filename
     * @return    bool
     */    
    function _file_delete($file)
    {
        $filepath = $this->log_path.$file;
        
        if (file_exists($filepath))
        {
            unlink($filepath);
            return TRUE;
        } else {
            return FALSE;
        }
    }

}
// END Log Class

/* End of file Log.php */
/* Location: ./application/libraries/Log.php */
#3

[eluser]Lockzi[/eluser]
I tried to optimize this file as well by collecting all the messages and writing to file only at __destruct() instead of everytime write_log is called, but apparently the class shutdown and fopen doesn't work well at all!

I hope someone else can find this useful.

Cheers,
Lockzi




Theme © iAndrew 2016 - Forum software by © MyBB