<?php
/* @desc；用于写日志
 * @auth: gilbert
 * @date；2017-04-19
 *
 */
class Common_Log {

    protected static $class;
    protected $_type;
    protected $_logPrefix = 'common';
    protected $_defaultType = 'default';
    protected $_logFileName;
    protected $_logPath;

    public function __construct() {

    }

    public static function getInstance()
    {
        if (!isset(self::$class)) {
            $c = __CLASS__;
            self::$class = new $c;
        }
        return self::$class;

    }

    protected function setType( $type ) {
        if( $type ) {
            $this->_defaultType = trim( $type );
        }
    }

    protected function setLogFileName() {
        $this->_logFileName = $this->_logPrefix.'_'.$this->_defaultType.'.log';
    }

    public function setLogPath( $path ) {
        if( $path ) {
            //去掉最后的分割符
            $length = mb_strlen( $path );
            $lastWord = mb_substr( $path, $length - 1, 1 );
            if( $lastWord == '\\' || $lastWord == '/') {
                $path = mb_substr( $path, 0, $length - 1 );
            }
            //如果路径存在
            if( file_exists( $path ) ) {
                $this->_logPath = $path;
            }
        }
    }

    protected function getLogFile() {
        return $this->_logPath . DIRECTORY_SEPARATOR .$this->_logFileName;
    }

    public function log( $type, $data ) {
        $this->setType( $type );
        $this->setLogFileName();
        if( !$this->_logPath ) {
            $path = implode( DIRECTORY_SEPARATOR, array( dirname( APPLICATION_PATH ), 'data', 'log' ) );
            $this->setLogPath( $path );
        }
        $file = $this->getLogFile();
        try{
            $hd = @fopen( $file, 'ab+');
            if( $hd ) {
                fwrite( $hd, var_export( $data, true )."\r\n" );
                fclose( $hd );
            }
        } catch( Exception $e) {
            //什么都不做
        }
    }

}