Debugging in Drupal 7

I can’t count the number of times I’ve seen print_r or var_export used while debugging code within Drupal. For those who use the devel module I see regular use of the dsm and dpm functions. In Drupal 7 this all changes for the better with the introduction of the debug function.

The Basics

Using the debug function is pretty straight forward, like using `dsm` or `print_r`. For example,
$node = node_load(123);
debug($node);

This will display the value of $node where php errors, notices, and warnings are usually displayed. This could be in the page or in the logs depending on how php is configured.

Why To Use Debug

There are 4 very good reasons to use debug over previous methods.
  • Since debug uses the built in php error handling the errors are displayed where php is configured to display them. If php is configured to only send them to the logs they will just show up there. This is really useful for debugging and getting the details of errors users are experiencing.
  • The previous bullet can be used during development or in production, depending on how php is configured, to capture valuable information. This is worth directly pointing out.
  • The debug function is common. Being in core its usage can be used across many modules consistently.
  • Quite often I see the debug output displaying at the top of a page throwing off the layout and look of the page to pick out a piece of information. `dpm` and `dsm` in devel do a good job not throwing that off. This can be used that way as well.
  • Works with Simpletest. Thanks for the info rfay

All The Options

The debug function has 3 arguments. It is pretty easy to just use `debug($data)` but there are cases where you want to do more than that.

The full options are:

debug($data, $label, $print_r);

The $data is pretty self explanatory. It can be anything you could pass through print_r or var_export. The $label allows for a custom label to be added. This is ideal when you are sending the information to a log and you want a key to search the logs for. The 3rd argument is whether to use print_r or var_export. The default is var_export. If you are interested between the two I’d suggest reading the manual pages.

I have to say I am quite happy with this addition to Drupal 7. It adds a bit more debugging power to Drupal.

Hat tip to chx for pointing out this function.