<?php
/** 
 * Log class:
 * (thanks to http://www.redips.net/php/write-to-log-file/ for the multiple insights writing this class)
 * - contains lfile, lwrite and lclose public methods
 * - lfile sets path and name of log file
 * - lwrite writes message to the log file (and implicitly opens log file)
 * - lclose closes log file
 * - first call of lwrite method will open log file implicitly
 * - message is written with the following format: [d/M/Y:H:i:s] (script name) message
 */
class Log {
    private $file_path, $message, $fp;
    
    function __construct( $path ){
		if ( $path != '' ) {
			try {
				$this->load( $path );
			} catch ( Exception $ex ) {
				// log exception
			}
		}
	}
    // set log file (path and name)
    public function load( $path ) {
        $this->file_path = $path;
    }
    
    
    
    /**
     * write message to the log file
     * 
     */
    public function write( $message ) {
        // if file pointer doesn't exist, then open log file
        if ( !is_resource( $this->fp ) ) {
            $this->lopen();
        }
        // define script name
        $script_name = pathinfo( $_SERVER['PHP_SELF'], PATHINFO_FILENAME );
        
        // define current time and suppress E_WARNING if using the system TZ settings
        // (don't forget to set the INI setting date.timezone)
        $time = @date( '[d/M/Y:H:i:s]' );
        
        // write current time, script name and message to the log file
        fwrite( $this->fp, "$time ($script_name) $message" . PHP_EOL );
    }

    /**
     * close log file (it's always a good idea to close a file when you're done with it)
     */

	public function lclose() {
		fclose( $this->fp );
	}
	
	/**
	 * open log file (private method)
	 */
	private function lopen() {
		$this->fp = fopen( $this->file_path, 'a') or exit( "Can't open $this->file_path !" );
    }
}
?>
