Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

customize log filename of codeigniter log_message()

Is there anyway to customize the filename of log generated by log_message() in CodeIgniter 2.1.0? By default, it's filename was generated based on the current date.

like image 525
planet x Avatar asked Apr 02 '12 05:04

planet x


2 Answers

log_message() function is common system function. Its using Log::write_log() method for logging error. Its not good hack the Core files. So you can extend Log library and overwrite write_log() function.

If you didnt extend your Log class yet. Create file application/libraries/MY_Log.php

class MY_Log extends CI_Log  {

    function MY_Log ()
    {
        parent::__construct();

        $this->ci =& get_instance();
    }

    public function write_log() { //here overriding
        if ($this->_enabled === FALSE)
        {
        return FALSE;
        }

        $level = strtoupper($level);

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

        /* HERE YOUR LOG FILENAME YOU CAN CHANGE ITS NAME */
        $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;
        }

        $message .= $level.' '.(($level == 'INFO') ? ' -' : '-').' ';
        $message .= date($this->_date_fmt). ' --> '.$msg."\n";

        flock($fp, LOCK_EX);
        fwrite($fp, $message);
        flock($fp, LOCK_UN);
        fclose($fp);

        @chmod($filepath, FILE_WRITE_MODE);
        return TRUE;
    }
}

Than log_message() function will work as your wish

like image 170
safarov Avatar answered Oct 23 '22 04:10

safarov


@safarov's answer is great, but a little out of date in terms of specific code, here's how to make your own:

  • Create your MY_Log class as described by @safarov but don't overwrite the method yet.
  • Find the file which contains the CI_Log class, in CI 3.1.10 it's called Log.php and if you're using composer you'll probably find it at /vendor/codeigniter/framework/system/core/Log.php
  • In that file, find the write_log function and copy the whole thing into your new class.
  • Edit that function to name the file how you wish.
  • Don't forget to update this function when you update CI!
like image 37
Darvanen Avatar answered Oct 23 '22 04:10

Darvanen