Monthly Archives: June 2010

Simple log class

As I am back to programming, I thought I’d start sharing some of the work I have been doing so that people can comment on it, use it and give me some feedback :). I wrote some small log class a few weeks ago and thought I might start off with that, so here it goes. This class simply creates a new csv file in /includes/logs every day and logs the information you want in it. It also passes on the class that uses it, to be able to trave it a little better.

class Log {
	// Stores the path of the logfile
	private $logPath;
	private $logFileName;
	private $fileReference;

	public function setLogPath($logPathIn) {
		$this->logPath = $logPathIn;
	}

	public function getLogPath() {
		return $this->logPath;
	}

	public function setLogFileName($logFileNameIn) {
		$this->logFileName = $logFileNameIn;
	}

	public function setFileReference($fileReferenceIn) {
		$this->fileReference = $fileReferenceIn;
	}

	public function getFileReference() {
		return $this->fileReference;
	}

	function __construct($textToWrite = "none", $class = "none") {
		$this->setLogPath(LOG_FILE_PATH);

		$time = time();
		$this->setLogFileName(date("d-m-y", $time) . ".log.csv");
		$this->setFileReference($this->logPath . $this->logFileName);

		if(!file_exists($this->getFileReference())) {
			$file = fopen($this->getFileReference(), "a+") or die("Something went wrong while creating the log file.");
			fwrite($file, "Time; Class; Error logged;n");
			fclose($file);
		}

		if($textToWrite != "none")
			$this->writeLog($textToWrite, $class);
	}

	function writeLog($textToWriteIn, $classIn = "none") {

		if($classIn != "none")
			$class = get_class($classIn);
		else
			$class = "none";
		$time = time();
		$date = date("H:i:s", $time);
		$textToWrite = $date . "; " . $class . "; " . $textToWriteIn;

		$file = fopen($this->fileReference, "a");
		fwrite($file, $textToWrite . "n");
		fclose($file);
	}
}

Please let me know if you have anything to add / comment