Creating a Custom Log Helper for the CodeIgniter Framework

Over the past few months, we've been working extensively with the PHP CodeIgniter framework. One thing that consistently slowed me down during debugging was the repetitive process of logging variables. Every time I needed to log a variable, I found myself typing out log_message('error', $your_variable)—a lengthy 18 characters every single time!

And that’s just for basic variables. If I wanted to log a boolean, object, or array, the process became even more time-consuming, often requiring additional if statements or extra formatting.

To simplify this process, I decided to write a small custom log helper. This helper makes logging easier by automatically handling different variable types, allowing for faster and more efficient debugging.

If you’re working with CodeIgniter and find logging as tedious as I did, you might find this helper useful too.


       
<?
if ( !function_exists('l') && !function_exists('l2') && !function_exists('get_parameter_value') )
{ 

  function get_parameter_value($param = null)
  {  

    if (is_null($param)){
      return 'NULL';

    }else if (!isset($param)){
      return "parameter is not SET";

    }else if(is_array($param)){
      if (empty($param)){
        return "empty array()";
      }else{
        return print_r($param, true);
      }

    }else if(is_string($param) || is_float($param) || is_int($param)){
 return $param;

    }else if (is_bool($param)){
      return ($param) ? 'TRUE' : 'FALSE';

    }else if (is_object($param)){   
      return var_export($param, true);

    }else{
      return "UNKNOWN TYPE";
   
    }

}

  function l($param1 = null, $msg_prefix = null)
  {   
    return log_message('error', (is_string($msg_prefix) ? " " 
      . $msg_prefix : "") . get_parameter_value($param1) );
  }

  function l2($param1 = null, $param2 = null)
  {   
    return log_message('error', get_parameter_value($param1) . " " . get_parameter_value($param2));
  }
 
}else{
  log_message('error', __FILE__ . ' - function l, l2, get_parameter_value  not created '); 
}

?>


       
<? 
  // example
  l($unknow_variable);  
?>


Comments

Popular posts from this blog

Skate Tricks Recognition Using Gyroscope

Play table

Counting dice and train wagons using computer vision