CI框架中 日志输出方法log_message()只允许输出字符串解决方案

1.修改CodeIgniter/index.php,添加如下:
define('ROOTDIR',dirname(__FILE__).'/');

2.修改CodeIgniter/application/config/config.php,如下:
$config['log_threshold'] = 1;
$config['log_path'] = ROOTDIR.'logs/';

3.修改CodeIgniter/system/core/Common.php,如下:
a.找到log_message()方法,将行
$_log->write_log($level, $message, $php_error);
替换为
$_log->appendLog($level, $message, $php_error);
b.添加如下方法(该方法根据实际需求情况决定是否需要,此处非必要)
    function write_message($message, $fileName = '')
    {
            static $_log;

            $_log =& load_class('Log');
            $_log->writeLog($message, $fileName);

    }
    
4.修改CodeIgniter/system/libraries/Log.php
a.添加属性
protected $_log = '';
b.找到属性$_levels,将行
protected $_levels = array('ERROR' => '1', 'DEBUG' => '2',  'INFO' => '3', 'ALL' => '4');
替换为
// modified by xcg add -1
protected $_levels = array('ERROR' => '1', 'DEBUG' => '2',  'INFO' => '3', 'ALL' => '4', 'NORMAL' => '-1');
c.在构造方法 __construct()最后添加如下语句
// add by xcg
register_shutdown_function(array(& $this, '__writeLog'));
d.添加如下方法
// add by xcg for cache log
public function appendLog($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;
}

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

$this->_log .= $msg;
}
// add by xcg for writing log when request terminated
function __writeLog()
        {
            $filepath = $this->_log_path.'ci-'.date('Y-m-d').".log";

            if ( ! $fp = @fopen($filepath, FOPEN_WRITE_CREATE))
            {
                    return FALSE;
            }
            flock($fp, LOCK_EX);
            fwrite($fp, $this->_log);
            flock($fp, LOCK_UN);
            fclose($fp);

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

        }

        // add by xcg for writing log to a special file.
function writeLog($message, $fileName = '')
   {
       $filepath = !empty($fileName)?$this->_log_path.$fileName:$this->_log_path.'ci-'.date('Y-m-d').".log";

               if ( ! $fp = @fopen($filepath, FOPEN_WRITE_CREATE))
               {
                       return FALSE;
               }

               $message = date($this->_date_fmt). '  '.print_r($message, true)."\n";

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

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

   }

5.最后,在apache或nginx的web目录下的CodeIgniter项目根目录下新建一个权限为777的logs文件夹

 

转载于:https://www.cnblogs.com/hgj123/p/3972868.html

你可能感兴趣的:(CI框架中 日志输出方法log_message()只允许输出字符串解决方案)