PHP日志LOG类定义与用法示例
作者:luyaran 时间:2023-09-10 20:02:56
本文实例讲述了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程序设计有所帮助。
来源:https://blog.csdn.net/luyaran/article/details/53214627
标签:PHP,日志
0
投稿
猜你喜欢
关于《回访确认》的几个问题
2009-08-24 12:43:00
三种在ES6中将非数组转换为数组的方法详情
2024-04-16 08:55:06
SQL2005查看死锁存储过程sp_who_lock
2024-01-12 20:34:13
分享下GET和POST的真正区别
2023-10-19 23:23:09
python 正则式使用心得
2021-09-17 14:39:49
PHP+JS实现文件分块上传的示例代码
2023-06-12 00:04:07
python实现层次聚类的方法
2023-05-03 22:26:13
python使用timeit时间模块
2023-03-05 16:27:37
如何使用Typora+MinIO+Python代码打造舒适协作环境
2023-11-12 15:12:10
IE多版本共存的解决方案——IETester(推荐)
2009-03-26 12:47:00
python去掉空格的一些常用方式
2022-02-10 04:45:34
vue通知提醒消息举例详解
2024-05-10 14:17:03
Python制作动态词频条形图的全过程
2021-04-25 11:14:52
Python实现的生成自我描述脚本分享(很有意思的程序)
2023-08-14 20:21:06
python删除文件夹中具有相同后缀类型文件的实战演练
2022-04-18 19:47:29
mysql5.7 设置远程访问的实现
2024-01-20 12:40:57
MacOS中 VSCode 安装 GO 插件失败问题的快速解决方法
2023-06-18 02:32:32
PHP实现的AES双向加密解密功能示例【128位】
2023-09-30 14:52:51
Navicat for MySQL定时备份数据库及数据恢复详解
2024-01-15 22:49:38
详解python实现线程安全的单例模式
2021-05-02 08:57:02