CodeIgniter Forums
Custom MY_Log.php - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Development (https://forum.codeigniter.com/forumdisplay.php?fid=6)
+--- Forum: CodeIgniter 3.x (https://forum.codeigniter.com/forumdisplay.php?fid=17)
+--- Thread: Custom MY_Log.php (/showthread.php?tid=65880)



Custom MY_Log.php - wolfgang1983 - 08-04-2016

I have just made a MY_Log.php so I can over ride log write function so that it can create log files for each of the log levels so it is easier to view.

I would like to know if it is safe and will not effect any thing else?

It now writes the files like
  • DEBUG-04-08-2016
  • ERROR-04-08-2016
  • INFO-04-08-2016
And only shows messages belong to that log

PHP Code:
<?php

class MY_Log extends CI_Log {

    public function write_log($level$msg)
    {
        if ($this->_enabled === FALSE)
        {
            return FALSE;
        }

        $level strtoupper($level);

        if (( ! isset($this->_levels[$level]) OR ($this->_levels[$level] > $this->_threshold))
            && ! isset($this->_threshold_array[$this->_levels[$level]]))
        {
            return FALSE;
        }

        $unlink_date date('d-m-Y'strtotime("-1 days"));
        
        $filepath_unlink 
$this->_log_path $level .'-'$unlink_date.'.'.$this->_file_ext;
          
          if 
(file_exists($filepath_unlink))
        {
           unlink($filepath_unlink);
        }

        $filepath $this->_log_path $level .'-'date('d-m-Y').'.'.$this->_file_ext;
        
        $message 
'';

        if ( ! file_exists($filepath))
        {
            $newfile TRUE;
            // Only add protection to php files
            if ($this->_file_ext === 'php')
            {
                $message .= "";
            }
        }

        if ( ! $fp = @fopen($filepath'ab'))
        {
            return FALSE;
        }

        flock($fpLOCK_EX);

        // Instantiating DateTime with microseconds appended to initial date is needed for proper support of this format
        if (strpos($this->_date_fmt'u') !== FALSE)
        {
            $microtime_full microtime(TRUE);
            $microtime_short sprintf("%06d", ($microtime_full floor($microtime_full)) * 1000000);
            $date = new DateTime(date('d-m-Y H:i:s.'.$microtime_short$microtime_full));
            $date $date->format($this->_date_fmt);
        }
        else
        
{
            $date date($this->_date_fmt);
        }

        $message .= $this->_format_line($level$date$msg);

        for ($written 0$length strlen($message); $written $length$written += $result)
        {
            if (($result fwrite($fpsubstr($message$written))) === FALSE)
            {
                break;
            }
        }

        flock($fpLOCK_UN);
        fclose($fp);

        if (isset($newfile) && $newfile === TRUE)
        {
            chmod($filepath$this->_file_permissions);
        }

        return is_int($result);
    }