Entries Tagged 'PHP' ↓

Simple PHP debugging with a log file

One of the biggest troubles with debugging in php (at least for me) is finding the error.  This brings me to the yell function.

The idea behind this function was first given to me by “Rob” at http://blog.tupleshop.com/2007/4/1/stupid-simple-logging (this link has since died)

His example is in rails, and I use it heavily

Here’s my example in php:


public function yell($string){
file_put_contents('yell.log', date("D M j G:i:s T Y") . " - " . $string . "\n", FILE_APPEND);
}

Looking through the code, all this yell function does is throws text into a file (with a quick timestamp before it).  That way you can see what values different variables have, etc.  It’s quick and dirty, but it brings a much greater view into your php at runtime.

The beauty of such a simplistic approach is that it’s easy to modify to do exactly what you need.

Here’s a good example, what if we wanted semi perminent logging, that is easy to turn on and off, with different levels:


public function yell($string, $importance = 1){
if ($importance >= $CURRENT_IMPORTANCE_LEVEL_CONSTANT){
file_put_contents('yell.log', date("D M j G:i:s T Y") . " - " . $string . "\n", FILE_APPEND);
}
}

This way depending on what we set the $CURRENT_IMPORTANCE_LEVEL_CONSTANT to, only certain lines will be shown, or you can set the constant very high, and not see any logs at all, etc.