首页 > 代码库 > PHP创建日志记录(已封装)
PHP创建日志记录(已封装)
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个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。