PHP: Logger and Timer Snippets

Hey. I’ve just started writing my simplest classes for a new content management micro-system in php, and I’d like to share some moments with you. These classes will probably be good for php noobs out there struggling in the world of object-oriented programming – go for the basics. The Logger class is just a text logger with simple functionality good for logics debugging. The Timer class will be great for performance debugging. Anyways, here we go:

class Logger
{
	public $filename;
	public $mode;
	public $timestamp;
	public $linebreak;

	public $contents;

	function __construct($filename = "log.log", $timestamp = "d.m.Y h:i:s", $linebreak = "rn", $mode = "a+")
	{
		$this->filename = $filename;
		$this->mode = $mode;
		$this->timestamp = date($timestamp);
		$this->linebreak = $linebreak;
		$this->contents = "";
	}

	function __destruct() { }

	function write($line)
	{
		$this->contents .= "{$this->timestamp} {$line} {$this->linebreak}";
	}

	function flush()
	{
		$handle = fopen($this->filename, $this->mode);
		fwrite($handle, $this->contents);
		fclose($handle);
		$this->contents = "";
	}
}

class Timer
{
	public $name;
	public $start;
	public $stop;
	public $format;

	const FORMAT_S = 0;
	const FORMAT_MS = 1;

	function __construct($name = "Timer", $autostart = false, $format = self::FORMAT_S)
	{
		$this->name = $name;
		$this->format = $format;
		if ($autostart) $this->start();
	}

	function __destruct() { }

	function start()
	{
		$this->start = microtime(true);
	}

	function stop()
	{
		$this->stop = microtime(true);
		$interval = $this->stop - $this->start;
		if ($this->format == self::FORMAT_MS) { $interval *= 1000; }
		return $interval;
	}
}

And this is how you use it:

$log = new Logger();
$log->write("some message");
$log->flush();

$timer = new Timer("Timer1", false, $this::FORMAT_MS);
$timer->start();
sleep(1);
echo "execution time: " . $timer->stop() . " ms";

I doubt that I need to explain this, but anyways, you’re always welcome to question in the comments. By the way, it seems that there’s a bug in php 5 that prevents us from using fwrite in class destructors, so I couldn’t flush on destruct.

About the author

Konstantin Kovshenin

WordPress Core Contributor, ex-Automattician, public speaker and consultant, enjoying life in Moscow. I blog about tech, WordPress and DevOps.