Organizational Research By

Surprising Reserch Topic

CodeIgniter query log hook



asked Jun 1, 2015 in codeinither by rajesh
0 votes
107 views



Related Hot Questions

1 Answer

0 votes
Whenever I use an ORM, such as CodeIgniter’s Active Record implementation, I find it very important to see the actual queries generated. Mainly because the danger of using an ORM is not knowing what happens in the background, which can introduce hard to find bugs and performance problems.

Below you’ll find a CodeIgniter hook that logs all database queries to a simple text file. I found this code useful in my first CodeIgniter project (since it’s from my first CI project, I think many revisions will follow, but you’ll get the idea).

/* config/hooks.php */
$hook['post_system'][] = array(
        'class' => 'QueryLogHook',
        'function' => 'log_queries',
        'filename' => 'QueryLogHook.php',
        'filepath' => 'hooks'

/* application/hooks/QueryLogHook.php */
class QueryLogHook {

    function log_queries() {    
        $CI =& get_instance();
        $times = $CI->db->query_times;
        $dbs    = array();
        $output = NULL;     
        $queries = $CI->db->queries;

        if (count($queries) == 0)
        {
            $output .= "no queries\n";
        }
        else
        {
            foreach ($queries as $key=>$query)
            {
                $output .= $query . "\n";
            }
            $took = round(doubleval($times[$key]), 3);
            $output .= "===[took:{$took}]\n\n";
        }

        $CI->load->helper('file');
        if ( ! write_file(APPPATH  . "/logs/queries.log.txt", $output, 'a+'))
        {
             log_message('debug','Unable to write query the file');
        }   
    }

}
answered Jun 1, 2015 by rajesh

...