PHP LOG使用心得(2)
<?php /** * create by :xiaojiang * PHP log 类 日志入库功能 仅供交流学习 */ class Config{ public static function getConfig (){ return array( 'LOG_LEVEL'=>75 //INFO ); } } class Log{ private $LogFile; private $logLevel; const DEBUG = 100; const INFO = 75; const NOTICE = 50; const WARNING =25; const ERROR = 10; const CRITICAL = 5; private function __construct(){} public static function getInstance($name){ return Log::backendManager($name); } public static function register($app,$params){ $urlDate = parse_url($params); if(!isset( $urlDate['scheme'])){ throw Exception('invalid log connection'); } @include('Logger/backend'.$urlDate['scheme'].'.class.php'); $className = $urlDate['scheme'].'backend'; if(!class_exists($className)){ throw new Exception('invalid className '.$className); } $backObj = new $className($params); Log::backendManager($app,$backObj); } private static function backendManager($name,$obj = null){ static $backends_arr; if(!isset($backends)){ $backends = null; } if(isset($obj)){ $backends_arr[$name] = $obj; }else{ if(!isset($backends_arr[$name])){ throw new Exception("the specified {$name} was not registered "); } return $backends_arr[$name]; } } public function levelToString($logLevel){ $ret = '[unknow]'; switch ($logLevel){ case LOG::DEBUG: $ret = 'LOG::DEBUG'; break; case LOG::INFO: $ret = 'LOG::INFO'; break; case LOG::NOTICE: $ret = 'LOG::NOTICE'; break; case LOG::WARNING: $ret = 'LOG::WARNING'; break; case LOG::ERROR: $ret = 'LOG::ERROR'; break; case LOG::CRITICAL: $ret = 'LOG::CRITICAL'; break; } return $ret; } } try{ LOG::register('error','http://localhost?user_name=root&dbname=test&table=test&password='); }catch(Exception $e){ echo $e->getMessage(); } try{ $logIns = LOG::getInstance('error'); }catch(Exception $e){ echo $e->getMessage(); } $logIns->LogMessage('哈哈',Log::INFO,'test'); /** * 文件 Logger/Httpbackend.class.php */ class Httpbackend{ public function __construct($params){ $Date = parse_url($params); parse_str($Date['query'],$url_params); $this->db = @mysql_connect($Date['host'],$url_params['user_name'],$url_params['password']); if(!is_resource($this->db)){ throw new Exception('invalid db resource'); } mysql_select_db($url_params['table'],$this->db); mysql_set_charset('utf8',$this->db); $this->logLevel = Config::getConfig('LOG_LEVEL'); } public function LogMessage($msg, $log_level = Log::info,$module=null){ if($log_level > $this->logLevel) return ; $sql = "INSERT INTO test (`msg`,module,add_time) VALUES ('{$msg}','{$module}',unix_timestamp())"; mysql_query($sql,$this->db); } } ?>
生命只有一次。