<?php

/**
 *--------------------------------------
 * log
 *--------------------------------------
 * @project		: pfa
 * @author		: cblee
 * @created		: 2012-9-23
 * @copyright	: (c)2012 AsThis
 *--------------------------------------
 */
defined('PFA_PATH') or exit('Access Denied');

class Log extends Pfa {
	const EMERG = 'EMERG';
	const ALERT = 'ALERT';
	const CRIT = 'CRIT';
	const ERR = 'ERR';
	const WARN = 'WARN';
	const NOTICE = 'NOTICE';
	const INFO = 'INFO';
	const DEBUG = 'DEBUG';
	const SQL = 'SQL';

	// log record type
	const SYSTEM = 0;
	const MAIL = 1;
	const TCP = 2;
	const FILE = 3;

	public static $log = array();
	public static $timeFormat = '[c]';

	/* record log */
	public static function record($message, $level = self::ERR, $record = false) {
		if($record || in_array($level, C('LOG.RECORD_LEVEL'))) {
			$now = date(self::$timeFormat);
			self::$log[] = "{$now} | URI:".$_SERVER['REQUEST_URI']." |{$level}: {$message}\r\n";
		}
	}

	/* save log, reference error_log() */
	public static function save($type = self::FILE, $destination = '', $extra = '') {
		if(empty($destination)) {
			$destination = LOG_PATH.D_S.date('y_m_d').'.log';
		}
		if(self::FILE == $type) {
			/* backup log when exceeding the configured size */
			if(is_file($destination) && floor(C('LOG.FILESIZE')) <= filesize($destination)) {
				rename($destination, dirname($destination).D_S.time().'-'.basename($destination));
			}
		}
		if(!empty(self::$log)) {
			error_log(implode('', self::$log), $type, $destination , $extra);
			self::$log = array();
			clearstatcache(); // clear log after save
		}
	}

	/* write log, reference error_log() */
	public static function write($message, $level = self::ERR, $type = self::FILE, $destination = '', $extra = '') {
		$now = date(self::$timeFormat);
		if(empty($destination)) {
			$destination = LOG_PATH.D_S.date('y_m_d').'.log';
		}
		if(self::FILE == $type) {
			/* backup log when exceeding the configured size */
			if(is_file($destination) && floor(C('LOG.FILESIZE')) <= filesize($destination)) {
				rename($destination, dirname($destination).D_S.time().'-'.basename($destination));
			}
		}
		error_log("{$now} | URI:".$_SERVER['REQUEST_URI']." | {$level}: {$message}\r\n", $type, $destination, $extra);
		clearstatcache(); // clear log after save
	}

	public function __construct() {}
}

?>