PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

A PHP log class for debuging

原创
2016-06-23 13:30:55 745浏览

分享一个我自己用的在 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。

日志条目默认采用北京时间。

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。