在现在项目中之前没有定义日志的方法,每次调试起来很麻烦,经常不能输出参数,只能用写日志的方法,一直用file_put_contents很烦躁,于是用了一点时间,写了这样一个方法:
<?php /* * 日志生成类 * write by vson * time:2017-06-14 * for:record and check * */ class logClass{ /* * 清除一个月之前的日志 * */ protected function logDirClear($logDir = '/tmp/log'){ if(is_dir($logDir)){ $dirHandle = opendir($logDir); while(($dirName = readdir($dirHandle)) != false){ $subDir = $logDir.'/'.$dirName; if($dirName == '.' || $dirName == '..'){ continue; }else{ $monthDate = date('Y-m-d', strtotime("- 30 day",time())); if(strtotime($monthDate) > strtotime($dirName)){ if(is_dir($subDir)){ $this->logFileClear($subDir); rmdir($subDir); } } } } closedir($dirHandle); } } protected function logFileClear($fileDir){ if(is_dir($fileDir)){ $fileHandle = opendir($fileDir); while(($fileName = readdir($fileHandle)) != false){ $subDir = $fileDir.'/'.$fileName; if($fileName == '.' || $fileName == '..'){ continue; }else{ if(is_dir($subDir)){ $this->logFileClear($subDir); rmdir($subDir); }else{ unlink($subDir); } } } closedir($fileHandle); } } /* * 生成新日志 * */ public function logWrite($fileName, $user, $content){ $this->logDirClear(); $logDir = '/tmp/log'; $now = date('Y-m-d'); $nowDir = $logDir.'/'.$now; if(!is_dir($nowDir)){mkdir($nowDir, 0777, true); } $fileDir = $nowDir.'/'.$fileName; $fileContent = $user.'在'.date('Y-m-d H:i:s').'时操作,内容为:'.$content; file_put_contents($fileDir, $fileContent." ==================== ", FILE_APPEND); } }