PHP日志LOG类定义与用法示例
程序员文章站
2022-05-26 13:39:08
本文实例讲述了php日志log类定义与用法。分享给大家供大家参考,具体如下:
本文实例讲述了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程序设计有所帮助。
上一篇: 本机开放的端口及使用该端口的进程的批处理
下一篇: 中国电信云计算转型雏形渐显