Welcome Guest, Not a member yet? Register   Sign In
[HOW TO] Log the calling class and method
#1

[eluser]Réjôme[/eluser]
Hello,

I had this simple need : to log the name of the calling class, and the method. Example :

Code:
DEBUG - 2011-04-23 09:21:29 - MY_Class - method --> This is the message

I worked on this for quite a long time and find this :

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

class MY_LOG extends CI_Log {

    /**
     * Write Log File
     *
     * Generally this function will be called using the global log_message() function
     *
     * @param    string    the error level
     * @param    string    the error message
     * @param    bool    whether the error is a native PHP error
     * @return    bool
     */
    public 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;
        }

        $filepath = $this->_log_path.'log-'.date('Y-m-d').EXT;
        $message  = '';

        if ( ! file_exists($filepath))
        {
            $message .= "<"."?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?".">\n\n";
        }

        if ( ! $fp = @fopen($filepath, FOPEN_WRITE_CREATE))
        {
            return FALSE;
        }
        
        /*
         * START OF MODIFICATION
         */
        $message .= $level.(($level == 'INFO') ? '  - ' : ' - ') . date($this->_date_fmt);

        $stack = debug_backtrace();
        // We are searching for the 2nd element of the $stack array beacause :
        // - $stack[0] is always taken by JG_Log->write_log()
        // - $stack[1] is always taken by log_message()
        if (isset($stack[2]['class'])) {
            $message .= ' - ' . $stack[2]['class'] . ' - ' . $stack[2]['function'];
        }

        $message .= ' --&gt; '.$msg."\n";
        /*
         * END OF MODIFICATION
         */
        
        flock($fp, LOCK_EX);
        fwrite($fp, $message);
        flock($fp, LOCK_UN);
        fclose($fp);
        
        @chmod($filepath, FILE_WRITE_MODE);
        return TRUE;
    }

}
// END Log Class

/* End of file Log.php */
/* Location: ./system/libraries/Log.php */

I hope this could help others ! :-)




Theme © iAndrew 2016 - Forum software by © MyBB