<?php
class Common_Log {
    protected  $_file;
    protected  $_path;
    protected  $_fileExisted = true;

    protected static $instance;

    public function __construct() {
        $this->setPath( dirname( APPLICATION_PATH ).'/data/log/' );
    }

    public function setPath( $path ) {
        if( file_exists( $path ) === false ) {
            if( false === mkdir( $path, '0777', true ) )
                $this->_fileExisted = false;
            else
                $this->_path = $path;
        } else {
            $this->_path = $path;
        }
        return $this;
    }

    public function setLogFile( $file ) {
        $this->_file = $this->_path.$file;
        return $this;
    }

    public function getLogFile() {
        return $this->_file;
    }

    public function getInstance() {
        if( !self::$instance ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    //记录日志
    public function log( $log ) {
        if( $this->_fileExisted === false )
            return false;

        $hd = fopen( $this->_file, 'ab+' );
        if( $hd ) {
            if( !is_string( $log ) && !is_numeric( $log ) ) {
                $log = var_export( $log, true );
            }
            fwrite( $hd, $log );
            fwrite( $hd, "\n" );
            fclose( $hd );
        }
    }
}