PHP建立日誌記錄(已封裝)

來源:互聯網
上載者:User

標籤:des   style   blog   color   os   io   for   檔案   ar   

 1 <?php 2  3 class Logs{ 4     private $_filepath;   //檔案路徑 5     private $_filename;   //檔案名稱 6     private $_filehandle; //檔案引擎 7  8  9      public function Logs($dir = null,$filename = null){10      11      $this->_filepath = empty($dir) ? ‘‘: $dir;12      $this->_filename = empty($filename) ? date(‘Y-m-d‘,time()).‘.log‘ : $filename;13     14     //建立路徑15      $path = $this->_createPath($this->_filepath,$this->_filename);16 17      if(!$this->_isExist($path)){//如果日誌目錄不存在18 19         if(!empty($this->_filepath)){  //如果路徑不存在20  21           if(!$this->_createDir($this->_filepath)){//建立路徑22            die("建立日誌目錄不成功");23           }24         }25 26         if(!$this->_createLogFile($path)){//建立日誌27          die("建立記錄檔不成功");28         }29      }30     31 32      $path = $this->_createPath($this->_filepath,$this->_filename);33      //建立記錄檔34      $this->_filehandle=fopen($path,"a+");35      }36     37     38      public function setLog($log) //寫日誌39     {40          //寫日誌41          $str = "";42          if(is_array($log)){43             foreach($log as $k => $v){44                $str .= $k." : ".$v."\n";45             }46          }else{47             $str = $log."\n";48          }49         50         51         if(!fwrite($this->_filehandle,$str)){//寫日誌52             die("寫日誌錯誤");53         }54      }55     56     57      private function _isExist($path){58      return file_exists($path);59      }60     61     62      private function _createDir($dir){   63          return is_dir($dir) or ($this->_createDir(dirname($dir)) and mkdir($dir, 0777));64      }65     66     67      private function _createLogFile($path){   68          $handle=fopen($path,"w"); //69          fclose($handle);70          return $this->_isExist($path);71      }72     73     74      private function _createPath($dir,$filename){75         if(empty($dir)){76         return $filename;77         }else{78         return $dir."/".$filename;79         }80      }81     82     83      function __destruct(){84      //關閉日誌85      fclose($this->_filehandle);86      }87  }88 ?>

 

PHP建立日誌記錄(已封裝)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.