public static function logAutoClean($msg = "", $fileName = 'common',$path='returnlog',$expireDays=10,$timeFlag=1) {
$fileName = str_replace('_','',$fileName);
$time = date('Y-m-d H:i:s');
$basePath = str_replace('\\','/',storage_path()) . '/logs/'.$path;
if(!is_dir($basePath)){
mkdir($basePath,0777,true);
}
//日志清理(5天一次)
if(!file_exists($basePath.'/CLEANED') || (time()-filemtime($basePath.'/CLEANED'))/86400>5){
$bakPath = str_replace('\\','/',storage_path()) . '/logs/bak';
is_dir($bakPath) || mkdir($bakPath,0777,true);
$handler = opendir($basePath);
while( ($filename = readdir($handler)) !== false ) {
if($filename != "." && $filename != ".." && is_file($filename)){
$filename1 = str_replace('.log','',$filename);
$fileArr = explode('_',$filename1);
if(isset($fileArr[1]) && isset($fileArr[2]) && date('Ymd')-$fileArr[1]>=$fileArr[2]){
//备份过期日志
rename($basePath.'/'.$filename,$bakPath.'/'.$filename);
//删除过期日志
//unlink($basePath.'/'.$filename);
}
}
}
closedir($handler);
file_put_contents($basePath.'/CLEANED','');//刷新文件的mtime
}
//写日志
if($timeFlag){
file_put_contents($basePath . '/' . $fileName . '_' .date('Ymd').'_'.$expireDays . '.log', $time . "\n" . $msg . PHP_EOL, FILE_APPEND);
}else{
file_put_contents($basePath . '/' . $fileName . '_' .date('Ymd').'_'.$expireDays . '.log', $msg . PHP_EOL, FILE_APPEND);
}
}
定期进行日志整理的php函数
关注
打赏