Monday, May 16, 2011

PHP Logger Class


/**
 * Logger
 *
 * Usage:
 *
 * Logger::getInstance()->setLogFileDirectory('/path/to/log/file/directory');
 *
 * Logger::getInstance()->info('Set info log message');
 * Logger::getInstance()->warning('Set warning log message');
 * Logger::getInstance()->error('Set error log message');
 * Logger::getInstance()->notice('Set notice log message');
 * Logger::getInstance()->debug('Set debug log message');
 *
 * Logger::getInstance()->enableDebug();
 * Logger::getInstance()->disableDebug();
 *
 * Logger::getInstance()->returnErrorMessages($boolean);
 */

class Logger {
    private $log_file_directory = ''; // Required
    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_file_name; // You can override the logfile name
    private $log_entry;         // information to be logged
    private $log_level;         // Log severity levels: error, warning, notice, debug, info
    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
    private $line_number_arr;   // Line number of where the logging event occurred
    private $debug_flag = false;
    private $log_file_date;     // datestamp for log file name
    private $return_error_messages = false; // Boolean: if false will echo error message else return error message
    private static $instance = null;

    private function __construct() {
        $this->first_run        = true;
        $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     = '';  
        $this->line_number_arr  = '';
$this->log_file_name = '';
    }

/**
* Get Instance
*
* @param
* @return object
*/
    public static function getInstance() {
        if(!isset(self::$instance)) {
            $c = __CLASS__;
            self::$instance = new $c;
        }
        return self::$instance;
    }

    /**
     * Enable Debug
     *
     * @param
     * @return
     */
    public function enableDebug() {
        $this->debug_flag = true;
    }

    /**
     * Disable Debug
     *
     * @param
     * @return
     */
    public function disableDebug() {
        $this->debug_flag = false;
    }

    /**
     * Info
     *
     * @param string
     * @return
     */
    public function info($info_message) {
        $this->log_level = 'info';
        $this->line_number_arr = debug_backtrace();
        return $this->addEntry($info_message);
    }

    /**
     * Error
     *
     * @param string
     * @return
     */
    public function error($error_message) {
        $this->log_level = 'error';
        $this->line_number_arr = debug_backtrace();
        return $this->addEntry($error_message);
    }

    /**
     * Warning
     *
     * @param string
     * @return
     */
    public function warning($warning_message) {
        $this->log_level = 'warning';
        $this->line_number_arr = debug_backtrace();
        return $this->addEntry($warning_message);
    }

    /**
     * Notice
     *
     * @param string
     * @return
     */
    public function notice($notice_message) {
        $this->log_level = 'notice';
        $this->line_number_arr = debug_backtrace();
        return $this->addEntry($notice_message);
    }

    /**
     * Debug
     *
     * @param string
     * @return
     */
    public function debug($debug_message) {
        if($this->debug_flag) {
            $this->log_level = 'debug';
            $this->line_number_arr = debug_backtrace();
            return $this->addEntry($debug_message);
        }      
    }

/**
     * Add Entry
     *
     * @param string
     * @return
     */
    private function addEntry($message) {
    if($this->log_file_directory == '') {
    $error_message = 'Please set the Log File Directory - Logger::getInstance()->setLogFileDirectory("/path/to/log/file/directory")'."\n";
   
if(!$this->return_error_messages) {
echo $error_message;
return;
}
return $error_message;
}
    $newline = "";
$tab = "";

if($this->getLogFileName() != '') {
$this->calling_script = $this->getLogFileName();
} else {
$this->calling_script = $this->getScriptBaseName();
}
       
        $this->log_file = $this->log_file_directory."/".$this->calling_script.".".$this->getLogDate().".log";
       
        if(!file_exists($this->log_file)) {
            $this->first_run = false;
            $this->line_count = 0;
        }

        if(!($this->fh = @fopen($this->log_file, 'a'))) {
        $error_message = 'Problem with Log File: '.$this->log_file."\n";

if(!$this->return_error_messages) {
echo $error_message;
return;
}
return $error_message;
        }

if($this->log_level == 'info') {
$tab = "\t";
}
           
        if($this->first_run) {
        $newline = "\n";
        }

$this->log_entry = $newline."[".date("Y-m-d H:i:s",mktime())."][line:".$this->line_number_arr[0]['line']."|".$this->log_level."]:\t".$tab.$message."\n";

        fwrite($this->fh, $this->log_entry);
        fclose($this->fh);
       
        $this->first_run = false;
        $this->line_count++;
    }

/**
     * Get Script Base Name
     *
     * @param
     * @return string
     */
    private function getScriptBaseName() {
        $this->setLogDate(date("Ymd"));
       
        $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 implode(".",array_slice($this->script_parts, 0, (count($this->script_parts) - 1)));
    }

/**
     * Set Log Date
     *
     * @param string
     * @return
     */
    private function setLogDate($value) {
        $this->log_file_date = $value;
    }
   
    /**
     * Get Log Date
     *
     * @param
     * @return string
     */
    private function getLogDate() {
        return $this->log_file_date;
    }

/**
* Set Log File Directory
*
* @param string
* @return
*/
public function setLogFileDirectory($log_file_directory) {
$this->log_file_directory = $log_file_directory;
}

/**
* Get Log File Directory
*
* @param
* @return string
*/
public function getLogFileDirectory() {
return $this->log_file_directory;
}

/**
* Return Error Message
*
* @param boolean
* @return
*/
public function returnErrorMessages($boolean) {
if(is_bool($boolean)) {
$this->return_error_messages = $boolean;
}
}

/**
* Set Log File name (Override)
*
* @param string
* @return
*/
public function setLogFileName($log_file_name) {
$this->log_file_name = $log_file_name;
}

/**
* Get Log File name
*
* @param
* @return string
*/
private function getLogFileName() {
return $this->log_file_name;
}
}

?>

1 comment:

Delwar said...

your blog is on of the best blogs. I pass. I have blog which is also containing PowerPoint I am delivering every events that count.
Using Templates..