本文实例讲述了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相关内容感兴趣的读者可查看本站专题:《PHP日志操作技巧总结》、《php文件操作总结》、《PHP数组(Array)操作技巧大全》、《PHP基本语法入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家PHP程序设计有所帮助。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。