2011年3月17日星期四

PHP实现的简单写日志类

很简单,把日志都写到了一个xml文件中,分日期保存日志。

其中add_element是添加dom的函数。

  1: <?php
  2: require_once dirname(__FILE__).'/../inc/config.php';
  3: require_once dirname(__FILE__).'/../inc/globe.php';
  4: class Log{
  5: 	
  6: 	public static function record($info,$level){
  7: 		try{
  8: 			if($level>=DEFAULT_LOG){
  9: 				$dir = dirname(__FILE__).'/../'.LOG_DATA_PATH;
 10: 				if(!is_dir($dir)){
 11: 					mkdir($dir,0777,true);
 12: 				}
 13: 				$filename = $dir.date('Ymd').'.xml';
 14: 				$dom = new DOMDocument('1.0', 'utf-8');
 15: 				if(is_file($filename)){
 16: 					$dom->load($filename);
 17: 					$logs = $dom->getElementsByTagname('logs')->item(0);
 18: 				}else{
 19: 					$pi = new DOMProcessingInstruction('xml-stylesheet','type="text/xsl" href="/xsl/log.xsl"');
 20: 					$dom->appendChild($pi);
 21: 					$logs = add_element($dom,'logs');
 22: 				}
 23: 				$log = add_element($logs,'log');
 24: 				
 25: 				add_element($log, 'time', date(DATE_RFC822));
 26: 				
 27: 				add_element($log, 'level', $level);
 28: 								
 29: 				add_element($log, 'info', $info);			
 30: 				
 31: 				file_put_contents($filename, $dom->saveXML(), LOCK_EX);
 32: 			}
 33: 		}catch(Exception $e){}
 34: 	}
 35: }
 36: ?>

没有评论:

发表评论