Thursday, September 11, 2014

CodeIgniter log

Custom log helper for CodeIgniter framework 

For the last few months we were working with the PHP CodeIgniter framework. Every time I was debugging and wanted to write down some variable I had to write this log_messge('error', $tog_this_var ). 18 characters! Horrible. If the variable was boolean, object or array I'd have to write more or add some if statements. So I decided to write a small helper. Maybe you will find it useful.

       
<?
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);  
?>


Share: