Drupal – adding debug messages to your custom module – Improved

As a follow up to ‘Drupal – adding debug messages to your custom module‘. I improved the code and wanted to share.
Now you can drop in a few functions and add one line to your hook_admin_settings function to get debugging functionality.
If you want to start with a baseline of functionality you can also update each of your functions to declare themselves in the debug messages. Which is handy for tracking down issues.

In the end you get the same addition to your GUI with control over how and when debug messages are used.
Screen Shot of the new checkboxes
You also get the same reporting output, to the screen, watchdog, or both:
Here’s a quick look at my watchdog log gui with both types of error reporting enabled:
Screen Shot of watchdog screen

All done with cleaner code.

Here’s the hook_admin_settings function with a small amendment:

<?
function mymodule_admin_settings($form, &$form_state) {
  #...
  $form = array_merge($form, _mymodule_debug_form()); //append settings form with debug fields
  return system_settings_form($form);
}//end function mymodule_admin_settings($form, &$form_state)
?>

The above adds the debug check-boxes to your modules existing admin fields.

Debug form fields that get included above:

<?
/**
 * Helper to produce mymodule debug configuration.
 *
 */
function _mymodule_debug_form() {
  // Debugging - fieldset for debug related fields
  $form&#91;'mymodule_debug'&#93; = array(
    '#type' => 'fieldset',
    '#title' => t('Debugging'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );

    $form['mymodule_debug']['mymodule_debug_message'] = array(
      '#type' => 'checkbox',
      '#title' => t('Enable debugging message feedback'),
      '#description' => t('Displays feedback in Drupal Messages'),
      '#default_value' => variable_get('mymodule_debug_message', FALSE),
      '#required' => FALSE
    );

    $form['mymodule_debug']['mymodule_debug_reporting'] = array(
      '#type' => 'checkbox',
      '#title' => t('Enable watchdog debugging feedback'),
      '#description' => t('Displays feedback messages in the Recent Log Entries (watchdog) Report'),
      '#default_value' => variable_get('mymodule_debug_reporting', FALSE),
      '#required' => FALSE
    );

  return $form;
} //function _mymodule_debug_form()
?>

That code can be essentially dropped into your module along with this next bit.

The actual debug log function

<?
/**
 * Helper to output debug messages.
 *
 * mymodule_debug_log($errMsgArr(array), &#91;$errLabel(string)='mymodule', $errSeverity(string)='status|warning|error', $force(bool)=FALSE&#93;)
 *
 */
function mymodule_debug_log($errMsgArr, $errLabel='mymodule', $errSeverity='status', $force=FALSE) {
  $watchdog_levels=watchdog_severity_levels();
  if ( $errMsgArr ) {
    if ( ! is_array($errMsgArr) && $errMsgArr !== ""){
      #$errMsgArr = implode(',', $errMsgArr);
      $errMsgArr = array($errMsgArr);
    }//end if ( ! is_array($errMsgArr) )
    foreach ( $errMsgArr as $errMsg ) {
      if ( variable_get('mymodule_debug_message', FALSE) || $force ){
        drupal_set_message(t($errMsg), $errSeverity);
      }//end if
      if ( variable_get('mymodule_debug_reporting', FALSE) || $force ) {
        #watchdog($errLabel,$errMsgArr);
        watchdog($errLabel,$errMsg,array(),array_search($errSeverity,$watchdog_levels));
      }//end if
    }//end loop
  }//end if $errMsgArr
}//function _mymodule_debug_form()
?>

So to use the debugging functionality you call the mymodule_debug_log function with a message where ever you need to. Like so: mymodule_debug_log('debug this!')
You can also specify additional vars such as

  • ‘error label’ (string)
    • This is handy for categorizing messages in watchdog
    • Default: the module name (so long as you replace the text ‘mymodule’)
  • error severity (string)
    • Options are:
      • ‘status’ (default)
      • ‘warning’
      • ‘error’
  • force (boolean)
    • This forces the error to the screen and watchdog even if no options have been enabled.
    • The force feature allows you to leverage the debug function for critical errors
    • Default: FALSE

To actually drop the above code fragments into your module you’d want to replace all occurrences of “mymodule” with ‘your module name’ first.

Example usage in the .module file.

Here I’ve added the mymodule_debug_log() call to an if statement and I’m using that status ‘error’ and $force=TRUE to push the error to the screen regardless of the debug mode:

<?
if ( ! $path ) {
  //force this debug message to the screen
  mymodule_debug_log('Notice: '. The required library can not be found., 'mymodule', 'error', TRUE);
}
&#91;/code&#93;

<h4>Here I've added the mymodule_debug_log() call to the function, simply declaring the function name:<h4>
<?
function mymodule_form_validate($form, &$form_state) {
  mymodule_debug_log('Running function mymodule_form_validate');
	...
}
?>

As with the former post. I like to add that debug message to all my functions in one fell swoop.

Here's the regex I used in the find & replace:
(Dreamweaver regex)
Find:

function (.*)((.*))[s]*{(.*)

Replace:

function $1($2) {$3
  mymodule_debug_log('Running function $1');

Here is all the code together in one code block so you can cut and paste and then replace occurrences of 'mymodule' before dropping it into your .module file:

<?
###################### Step 1 ######################
## Replace all occurances of mymodule with your module name

###################### Step 2 ######################
## Insert this line at the end of your (hook)_admin_settings() function but before the 'return system_settings_form'
### (Hint: Search for:
return system_settings_form

Replace with:
$form = array_merge($form, _uoasymptote_debug_form()); //append settings form with debug fields
  return system_settings_form

  ### It will look something like this:
  function mymodule_admin_settings($form, &$form_state) {
    #...
    $form = array_merge($form, _mymodule_debug_form()); //append settings form with debug fields
    return system_settings_form($form);
  }//end function mymodule_admin_settings($form, &$form_state)
  # The above adds the debug check-boxes to your modules existing admin fields.

###################### Step 3 ######################
##Insert the following two functions after the above function

/**
 * Helper to produce mymodule debug configuration.
 *
 */
function _mymodule_debug_form() {
  // Debugging - fieldset for debug related fields
  $form&#91;'mymodule_debug'&#93; = array(
    '#type' => 'fieldset',
    '#title' => t('Debugging'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );

    $form['mymodule_debug']['mymodule_debug_message'] = array(
      '#type' => 'checkbox',
      '#title' => t('Enable debugging message feedback'),
      '#description' => t('Displays feedback in Drupal Messages'),
      '#default_value' => variable_get('mymodule_debug_message', FALSE),
      '#required' => FALSE
    );

    $form['mymodule_debug']['mymodule_debug_reporting'] = array(
      '#type' => 'checkbox',
      '#title' => t('Enable watchdog debugging feedback'),
      '#description' => t('Displays feedback messages in the Recent Log Entries (watchdog) Report'),
      '#default_value' => variable_get('mymodule_debug_reporting', FALSE),
      '#required' => FALSE
    );

  return $form;
}//end function _mymodule_debug_form()

/**
 * Helper to output debug messages.
 *
 * mymodule_debug_log($errMsgArr(array), [$errLabel(string)='mymodule', $errSeverity(string)='status|warning|error', $force(bool)=FALSE])
 *
 */
function mymodule_debug_log($errMsgArr, $errLabel='mymodule', $errSeverity='status', $force=FALSE) {
  $watchdog_levels=watchdog_severity_levels();
  if ( $errMsgArr ) {
    if ( ! is_array($errMsgArr) && $errMsgArr !== ""){
      #$errMsgArr = implode(',', $errMsgArr);
      $errMsgArr = array($errMsgArr);
    }//end if ( ! is_array($errMsgArr) )
    foreach ( $errMsgArr as $errMsg ) {
      if ( variable_get('mymodule_debug_message', FALSE) || $force ){
        drupal_set_message(t($errMsg), $errSeverity);
      }//end if
      if ( variable_get('mymodule_debug_reporting', FALSE) || $force ) {
        #watchdog($errLabel,$errMsgArr);
        watchdog($errLabel,$errMsg,array(),array_search($errSeverity,$watchdog_levels));
      }//end if
    }//end loop
  }//end if $errMsgArr
}//end function _mymodule_debug_form()

###################### Step 4 (optional) ######################
Find (ex. w/ Dreamweaver regex):
function (.*)((.*))[s]*{(.*)

Replace:
function $1($2) {$3
  mymodule_debug_log('Running function $1');

## Note: when you do this be sure to remove the mymodule_debug_log(...) call from with in the function uoasymptote_debug_log() or you will get unlimited recursion that will gobble up your ram and white-screen your site.

Leave a Comment