<?

class trace
{
	var $log_email;
	var $log_file;

	var $log_level;
	var $message;
	var $message_type;

	function trace()
	{
		global $config;

		$this->log_file  = $config['LOG_FILE'];
		$this->log_email = $config['LOG_EMAIL'];
	}

	function log()
	{
		// If message is to be appended to a log file
		if ($this->message_type == 3)
		{
			if (! $this->log_file){
				return;
			}

			$destination = $this->log_file;
		}
		else if ($this->message_type == 1)  // If message is to be sent to an email address
		{
			$destination = $this->log_email;
		}

		if (substr($this->message, -1) != "\n"){
				$this->message .= "\n";
		}

		$message = date('Y-m-d H:i:s') . " - " . $this->log_level . ' - ' . $this->getMessageLocation() . $this->message;
		error_log($message, $this->message_type, $destination);
	}

	function error($message, $message_type = 3)
	{
		$this->log_level = "ERROR";
		$this->message = $message;
		$this->message_type = $message_type;
		$this->log();
	}

	function warn($message, $message_type = 3)
	{
		$this->log_level = "WARNING";
		$this->message = $message;
		$this->message_type = $message_type;
		$this->log();
	}

	function info($message, $message_type = 3)
	{
		$this->log_level = "INFO";
		$this->message = $message;
		$this->message_type = $message_type;
		$this->log();
	}

	function debug($message, $message_type = 3)
	{
		$this->log_level = "DEBUG";
		$this->message = $message;
		$this->message_type = $message_type;
		$this->log();
	}

	function getMessageLocation()
	{
		// __FILE__.':'.__LINE__.'/'.__CLASS__.'->'.__FUNCTION__;

		$arr = debug_backtrace();

		$file_name = basename($arr[2]['file']);
		if ($this->log_level != "INFO")
		{
			$message_location .= '['.$file_name.':'.$arr[2]['line'].']';
		}

		$pos = strrpos($file_name, ".class.php");
		// exit($file_name . ',' . $pos);
		if ($pos !== false) {
    	$message_location .= '['.$arr[3]['class'].'->'.$arr[3]['function'].']';
		}

		if (!empty($message_location)) $message_location .= ' - ';

		return $message_location;
	}

}

?>