分享一個我自己用的在 WordPress 開發中用得到的一個調試日誌類。
dir = dirname($main_file).DIRECTORY_SEPARATOR.'debug'.DIRECTORY_SEPARATOR; $file_name = 'debug_'.md5($main_file).'.log'; $this->debug_file_name = (function_exists('apply_filters'))?apply_filters('cwp_debug_log_file_name',$file_name).'.log':$file_name.'.log'; $this->f_path = $this->dir.$this->debug_file_name; $this->check_log_file(); } /** * adding log item * @param string $text : adding content */ public function add($text) { date_default_timezone_set('Asia/Shanghai'); if(is_array($text)||is_obeject($text)){ $text = json_encode($text); } $fp = fopen( $this->f_path,"a"); flock($fp, LOCK_EX) ; fwrite($fp,"".date("Y-m-d H:i:s",time())."\n".$text."\n\n"); flock($fp, LOCK_UN); fclose($fp); //return true; // } /** * checking the log file and path. * @return null */ private function check_log_file(){ $is_dir = is_dir($this->dir); $is_file = file_exists($this->f_path); if($is_dir && $is_file) return; if(!$is_dir||!$is_file){ if(!$is_dir){ $md = mkdir($this->dir,0777,true); } if(!$is_file){ $fp = fopen( $this->f_path,"a"); fclose($fp); } } } }/*//CLASS*/}/*ALL DONE.*/?>
以 WordPress 外掛程式為例的用例:
在外掛程式主檔案的適當位置加入(假如上述代碼放置在class-coolwp-debug-log.php檔案中):
$this->is_debug = true;if($this->is_debug){ require_once( plugin_dir_path(__FILE__).'classes/class-coolwp-debug-log.php'); $this->Log = new CoolWP_com_Log();}
如果在外掛程式主檔案中將__FILE__定義為常量 SOMEONE_THIS,那麼,可以將SOMEONE_THIS 作為參數傳給CoolWP_com_Log(),例如:
$this->Log = new CoolWP_com_Log(SOMEONE_THIS);
傳不傳參數的區別是記錄檔的位置不同,如果不傳參數,記錄檔位於class-coolwp-debug-log.php所在目錄下的debug目錄下;如果傳遞了SOMEONE_THIS參數,那麼,記錄檔位於外掛程式主目錄下的debug目錄下。記錄檔的檔案名稱為debug_*******log。
日誌條目預設採用北京時間。