Simple Logger
If you are programming in PHP, I bet you are using “prints and dies” to debug your code. I know its the easiest way to debug any web based program. But some time you “die” just don’t work, you need to know much more about programs flow and what’s 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 “Prints”. 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
class Logger { var $m_hFile; function Logger($file) { $this->m_hFile = $file; } function log($message) { if(!$handle = @fopen($this->m_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:
1 2 |
$logger = new Logger("mylog.txt"); $logger->log("I am at line 9, writing logs"); |
Isn’t it simple! I hope you liked and find useful the PHP Logger.