PHP Log LOG Class Definition and Usage Example
- 2021-11-02 00:09:51
- OfStack
This article illustrates the PHP log LOG class definition and usage. Share it for your reference, as follows:
<?php
/**
* PHP log Class
*/
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');
?>
Run the program and generate the test. txt file in the current directory as follows (here is the result of running 3 times):
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
For more readers interested in PHP related contents, please check the topics of this site: "Summary of PHP Log Operation Skills", "Summary of php File Operation Skills", "Encyclopedia of PHP Array (Array) Operation Skills", "Introduction to PHP Basic Grammar", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation Skills" and "Summary of php Common Database Operation Skills"
I hope this article is helpful to everyone's PHP programming.