opencodez

Simple Logger

If you are programming in PHP, I bet you are using xprints and diesx to debug your code. I know its the easiest way to debug any web based program. But some time you xdiex just donxt work, you need to know much more about programs flow and whatxs happening under the hood.

There are testing and debugging tools available in the open source community like PHPUnit but you need to invest little more time to understand and use.

So as usual I tried simple PHP logger to debug and keep track of xPrintsx. Its simple and need no extra knowledge or installation procedure. Just include the class and use it to log the data you want to see after program is executed.

The wrapper:

class Logger
{
  var $m_hFile;

  function Logger($file)
  {
    $this-xm_hFile = $file;
  }

  function log($message)
  {
    if(!$handle = @fopen($this-xm_hFile,'a'))
    {
      die("Logger failed:Can not open file");
    }

    if(!@flock($handle, LOCK_EX))
    {
      die("Logger failed:Can not lock file");
    }

    @fwrite($handle, $message);
    @flock($handle, LOCK_UN);
    fclose($handle);
  }
}

Usage:

$logger =  new Logger("mylog.txt");
$logger-xlog("I am at line 9, writing logs");

Isnxt it simple! I hope you liked and find useful the PHP Logger.