您好,登錄后才能下訂單哦!
這篇文章給大家介紹怎么在PHP中定義一個日志LOG類,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
具體如下:
<?php /** * PHP log 類 */ class Config{ public static function getConfig (){ return array( 'LOG_FILE'=>'test.txt', '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(){ $cfg = Config::getConfig(); $this->logLevel = isset($cfg['LOG_LEVEL']) ? $cfg['LOG_LEVEL']:LOG::INFO; if(!isset($cfg['LOG_FILE']) && strlen($cfg['LOG_FILE'])){ throw new Exception('can\'t set file to empty'); } $this->LogFile = @fopen($cfg['LOG_FILE'],'a+'); if(!is_resource($this->LogFile)){ throw new Exception('invalid file Stream'); } } public static function getInstance(){ static $obj; if(!isset($obj)){ $obj = new Log(); } return $obj; } public function LogMessage($msg, $logLevel = Log::INFO,$module = null){ if($logLevel > $this->logLevel){ return ; } date_default_timezone_set('Asia/shanghai'); $time = strftime('%x %X',time()); $msg = str_replace("\t",'',$msg); $msg = str_replace("\n",'',$msg); $strLogLevel = $this->levelToString($logLevel); if(isset($module)){ $module = str_replace(array("\n","\t"),array("",""),$module); } $logLine = "$time\t$msg\t$strLogLevel\t$module\r\n"; fwrite($this->LogFile,$logLine); } 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; } } $logIns = LOG::getInstance(); //print_r($logIns); $logIns->logMessage("test",LOG::INFO,'myTest'); ?>
運行程序,在當前目錄下生成test.txt文件內容如下(這里是運行3次的結果):
09/06/18 14:56:20 test LOG::INFO myTest
09/06/18 14:56:21 test LOG::INFO myTest
09/06/18 14:56:22 test LOG::INFO myTest
關于怎么在PHP中定義一個日志LOG類就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。