Best suggestion will be the accepted answer
Class:
<?php
class LogInfo {
private $first_run; // Flag to add line break at the beginning of script execution
private $calling_script; // Base name of the calling script
private $log_file; // log file path and name
private $log_entry; // information to be logged
private $log_level; // Log severity levels: error, warning, notice, info (default)
private $log_level_arr; // Array of accepted log levels
private $fh; // File handle
private $file_name; // File path and name
private $file_parts; // Array of $file_name
private $script_name; // Script Name
private $script_parts; // Array of $script_name
function __construct() {
$this->first_run = true;
$this->log_level_arr = array(
'info'=>'info', // default
'error'=>'error',
'warning'=>'warning',
'notice'=>'notice',
);
$this->calling_script = '';
$this->log_file = '';
$this->log_entry = '';
$this->log_level = '';
$this->fh = '';
$this->file_name = '';
$this->file_parts = '';
$this->script_name = '';
$this->script_parts = '';
}
/**
* log detailed information into calling script log files
*/
public function logInfo($info, $level = 'info') {
if(array_key_exists($level,$this->log_level_arr)) {
$this->log_level = $level;
} else {
$this->log_level = 'undefined';
}
$this->calling_script = $this->getScriptBaseName();
$this->log_file = dirname(__FILE__)."/logs/".$this->calling_script.".log";
$this->fh = fopen($this->log_file, 'a') or die("Can't open log file: ".$this->log_file);
if($this->first_run) {
$this->log_entry = "\n[" . date("Y-m-d H:i:s", mktime()) . "][" .$this->log_level."]:\t".$info."\n";
} else {
$this->log_entry = "[" . date("Y-m-d H:i:s", mktime()) . "][" .$this->log_level."]:\t".$info."\n";
}
fwrite($this->fh, $this->log_entry);
fclose($this->fh);
$this->first_run = false;
}
/**
* return the base name of the calling script
*/
private function getScriptBaseName() {
$this->file_name = $_SERVER["SCRIPT_NAME"];
$this->file_parts = explode('/', $this->file_name);
$this->script_name = $this->file_parts[count($this->file_parts) - 1];
$this->script_parts = explode('.', $this->script_name);
return $this->script_parts[0];
}
}
?>
How to call:
$log = new LogInfo();
$txt = "This is comment";
$log->logInfo($txt." 1",'error');
$log->logInfo($txt." 2",'new');
$log->logInfo($txt." 3",'warning');
$log->logInfo($txt." 4",'notice');
$log->logInfo($txt." 5",'info');
$log->logInfo($txt." 6");