PHP日志LOG类定义与用法示例
发布:smiling 来源: PHP粉丝网 添加日期:2021-10-28 13:59:47 浏览: 评论:0
这篇文章主要介绍了PHP日志LOG类定义与用法,结合实例形式分析了日志log的具体定义及使用方法,涉及php文件读写、日期时间及字符串等相关操作技巧,需要的朋友可以参考下。
本文实例讲述了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
Tags: PHP日志LOG类
推荐文章
热门文章
最新评论文章
- 写给考虑创业的年轻程序员(10)
- PHP新手上路(一)(7)
- 惹恼程序员的十件事(5)
- PHP邮件发送例子,已测试成功(5)
- 致初学者:PHP比ASP优秀的七个理由(4)
- PHP会被淘汰吗?(4)
- PHP新手上路(四)(4)
- 如何去学习PHP?(2)
- 简单入门级php分页代码(2)
- php中邮箱email 电话等格式的验证(2)