2016-08-04 64 views
0

Unink日誌文件,我想之前已創建前一天笨

我有一個自定義應用程序>核心> MY_Log.php文件取消鏈接創建那一天的文件,它創建一個日誌爲每個錯誤水平。爲了更容易閱讀。

  • 日誌> DEBUG-04-08-2016.php
  • 日誌> ERROR-04-08-2016.php
  • 日誌> INFO-04-08-2016.php
  • 日誌> DEBUG-03-08-2016.php
  • 日誌> ERROR-03-08-2016.php
  • 日誌> INFO-03-08-2016.php

問題我該如何修改write_log,以便刪除/取消鏈接前一天創建的文件?

<?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; 
     } 

     $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($fp, LOCK_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($fp, substr($message, $written))) === FALSE) 
      { 
       break; 
      } 
     } 

     flock($fp, LOCK_UN); 
     fclose($fp); 

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

     return is_int($result); 
    } 
} 

回答

1

使用

$config['log_threshold'] = 1; 

僅供錯誤消息的第一,所以會有數少的文件

添加以下代碼只是$filepath;之前刪除以前的日期的日誌

$unlink_date = date('Y-m-d',strtotime("-1 days")); 

$filepath_unlink = $this->_log_path . $level .'-'. $unlink_date.'.'.$this->_file_ext; 

if (file_exists($filepath_unlink)) 
{ 
    unlink($filepath_unlink); 
} 
+0

它的工作,但仍然想'$ config ['log_thre shold'] = 4;' – user4419336

+0

確定沒有問題,很棒的kool。 upvote這個答案 –