How to debug Drupal or ... How I fell in love with the debug() function

Let's say you see recurring error messages in your db log file and you want to try and pinpoint the issue to be able to apply a fix.
So, how do you go about debugging your code?

Well, there are many different ways. You could go old-school and use

var_dump();

or

print_r();

.
Or you could go a step further and use

debug_backtrace();

to try and pinpoint the source of the error.

Alternatively of course you can always install xdebug or the Zend php debugging extension - but for most shared hosting this may be impossible.

So here are a few other options we have (i'll try and add more if and when I come across them ;-) ):

- Use the Devel Module.

- Using

debug_backtrace();

:

Example1:

        $trace = debug_backtrace();
        $backtrace_lite = array();
        foreach( $trace as $call ) {
          $backtrace_lite[] = $call['function']."    ".$call['file']."    line ".$call['line'];
        }
        // use drupals own debug() function
        debug( $backtrace_lite, "TRACE", true );

Example 2:

        $bt = debug_backtrace();
        foreach ($bt as $key => $value) {
          if ($key == 0) {
            continue;
          }
          unset($bt[$key]['args']);
          unset($bt[$key]['object']);
        }
        drupal_set_message(str_replace('    ', '    ', nl2br(htmlentities(print_r($bt, TRUE)))));